import { sql } from 'drizzle-orm';
import { boolean, doublePrecision, index, integer, jsonb, pgEnum, pgTable, serial, text, timestamp, uuid, varchar } from 'drizzle-orm/pg-core';
import { AreasServed, LicensedIn } from '../models/db.model';
export const PG_CONNECTION = 'PG_CONNECTION';
export const genderEnum = pgEnum('gender', ['male', 'female']);
export const customerTypeEnum = pgEnum('customerType', ['buyer', 'seller', 'professional']);
export const customerSubTypeEnum = pgEnum('customerSubType', ['broker', 'cpa', 'attorney', 'titleCompany', 'surveyor', 'appraiser']);
export const listingsCategoryEnum = pgEnum('listingsCategory', ['commercialProperty', 'business']);
export const subscriptionTypeEnum = pgEnum('subscriptionType', ['free', 'professional', 'broker']);

// Neue JSONB-basierte Tabellen
export const users_json = pgTable(
  'users_json',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    email: varchar('email', { length: 255 }).notNull().unique(),
    data: jsonb('data'),
  },
  table => ({
    emailIdx: index('idx_users_json_email').on(table.email),
  }),
);

export const businesses_json = pgTable(
  'businesses_json',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    email: varchar('email', { length: 255 }).references(() => users_json.email),
    data: jsonb('data'),
  },
  table => ({
    emailIdx: index('idx_businesses_json_email').on(table.email),
  }),
);

export const commercials_json = pgTable(
  'commercials_json',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    email: varchar('email', { length: 255 }).references(() => users_json.email),
    data: jsonb('data'),
  },
  table => ({
    emailIdx: index('idx_commercials_json_email').on(table.email),
  }),
);

export const listing_events_json = pgTable(
  'listing_events_json',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    email: varchar('email', { length: 255 }),
    data: jsonb('data'),
  },
  table => ({
    emailIdx: index('idx_listing_events_json_email').on(table.email),
  }),
);

// Bestehende Tabellen bleiben unverändert
export const users = pgTable(
  'users',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    firstname: varchar('firstname', { length: 255 }).notNull(),
    lastname: varchar('lastname', { length: 255 }).notNull(),
    email: varchar('email', { length: 255 }).notNull().unique(),
    phoneNumber: varchar('phoneNumber', { length: 255 }),
    description: text('description'),
    companyName: varchar('companyName', { length: 255 }),
    companyOverview: text('companyOverview'),
    companyWebsite: varchar('companyWebsite', { length: 255 }),
    offeredServices: text('offeredServices'),
    areasServed: jsonb('areasServed').$type<AreasServed[]>(),
    hasProfile: boolean('hasProfile'),
    hasCompanyLogo: boolean('hasCompanyLogo'),
    licensedIn: jsonb('licensedIn').$type<LicensedIn[]>(),
    gender: genderEnum('gender'),
    customerType: customerTypeEnum('customerType'),
    customerSubType: customerSubTypeEnum('customerSubType'),
    created: timestamp('created'),
    updated: timestamp('updated'),
    subscriptionId: text('subscriptionId'),
    subscriptionPlan: subscriptionTypeEnum('subscriptionPlan'),
    location: jsonb('location'),
    showInDirectory: boolean('showInDirectory').default(true),
  },
  table => ({
    locationUserCityStateIdx: index('idx_user_location_city_state').on(
      sql`((${table.location}->>'name')::varchar), ((${table.location}->>'state')::varchar), ((${table.location}->>'latitude')::float), ((${table.location}->>'longitude')::float)`,
    ),
  }),
);

export const businesses = pgTable(
  'businesses',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    email: varchar('email', { length: 255 }).references(() => users.email),
    type: varchar('type', { length: 255 }),
    title: varchar('title', { length: 255 }),
    description: text('description'),
    price: doublePrecision('price'),
    favoritesForUser: varchar('favoritesForUser', { length: 30 }).array(),
    draft: boolean('draft'),
    listingsCategory: listingsCategoryEnum('listingsCategory'),
    realEstateIncluded: boolean('realEstateIncluded'),
    leasedLocation: boolean('leasedLocation'),
    franchiseResale: boolean('franchiseResale'),
    salesRevenue: doublePrecision('salesRevenue'),
    cashFlow: doublePrecision('cashFlow'),
    supportAndTraining: text('supportAndTraining'),
    employees: integer('employees'),
    established: integer('established'),
    internalListingNumber: integer('internalListingNumber'),
    reasonForSale: varchar('reasonForSale', { length: 255 }),
    brokerLicencing: varchar('brokerLicencing', { length: 255 }),
    internals: text('internals'),
    imageName: varchar('imageName', { length: 200 }),
    slug: varchar('slug', { length: 300 }).unique(),
    created: timestamp('created'),
    updated: timestamp('updated'),
    location: jsonb('location'),
  },
  table => ({
    locationBusinessCityStateIdx: index('idx_business_location_city_state').on(
      sql`((${table.location}->>'name')::varchar), ((${table.location}->>'state')::varchar), ((${table.location}->>'latitude')::float), ((${table.location}->>'longitude')::float)`,
    ),
    slugIdx: index('idx_business_slug').on(table.slug),
  }),
);

export const commercials = pgTable(
  'commercials',
  {
    id: uuid('id').primaryKey().defaultRandom().notNull(),
    serialId: serial('serialId'),
    email: varchar('email', { length: 255 }).references(() => users.email),
    type: varchar('type', { length: 255 }),
    title: varchar('title', { length: 255 }),
    description: text('description'),
    price: doublePrecision('price'),
    favoritesForUser: varchar('favoritesForUser', { length: 30 }).array(),
    listingsCategory: listingsCategoryEnum('listingsCategory'),
    draft: boolean('draft'),
    imageOrder: varchar('imageOrder', { length: 200 }).array(),
    imagePath: varchar('imagePath', { length: 200 }),
    slug: varchar('slug', { length: 300 }).unique(),
    created: timestamp('created'),
    updated: timestamp('updated'),
    location: jsonb('location'),
  },
  table => ({
    locationCommercialsCityStateIdx: index('idx_commercials_location_city_state').on(
      sql`((${table.location}->>'name')::varchar), ((${table.location}->>'state')::varchar), ((${table.location}->>'latitude')::float), ((${table.location}->>'longitude')::float)`,
    ),
    slugIdx: index('idx_commercials_slug').on(table.slug),
  }),
);

export const listing_events = pgTable('listing_events', {
  id: uuid('id').primaryKey().defaultRandom().notNull(),
  listingId: varchar('listing_id', { length: 255 }),
  email: varchar('email', { length: 255 }),
  eventType: varchar('event_type', { length: 50 }),
  eventTimestamp: timestamp('event_timestamp').defaultNow(),
  userIp: varchar('user_ip', { length: 45 }),
  userAgent: varchar('user_agent', { length: 255 }),
  locationCountry: varchar('location_country', { length: 100 }),
  locationCity: varchar('location_city', { length: 100 }),
  locationLat: varchar('location_lat', { length: 20 }),
  locationLng: varchar('location_lng', { length: 20 }),
  referrer: varchar('referrer', { length: 255 }),
  additionalData: jsonb('additional_data'),
});
