import { pgTable, text, serial, integer, boolean, decimal, jsonb, timestamp } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { z } from "zod";

export const users = pgTable("users", {
  id: serial("id").primaryKey(),
  username: text("username").notNull().unique(),
  password: text("password").notNull(),
  isAdmin: boolean("is_admin").default(false),
});

export const insertUserSchema = createInsertSchema(users).pick({
  username: true,
  password: true,
  isAdmin: true,
});

export const projectTypes = pgTable("project_types", {
  id: serial("id").primaryKey(),
  name: text("name").notNull(),
  description: text("description").notNull(),
  price: decimal("price", { precision: 10, scale: 2 }).default("0"),
  subOptions: jsonb("sub_options").$type<{
    id: string;
    name: string;
    description?: string;
    price: string;
  }[] | null>(),
  hasSubOptions: boolean("has_sub_options").default(false),
});

export const insertProjectTypeSchema = createInsertSchema(projectTypes).pick({
  name: true,
  description: true,
  price: true,
  subOptions: true,
  hasSubOptions: true,
});

export const legalStatuses = pgTable("legal_statuses", {
  id: serial("id").primaryKey(),
  name: text("name").notNull(),
  description: text("description").notNull(),
  requiredDocuments: jsonb("required_documents").$type<string[]>(),
});

export const insertLegalStatusSchema = createInsertSchema(legalStatuses).pick({
  name: true,
  description: true,
  requiredDocuments: true,
});

export const centers = pgTable("centers", {
  id: serial("id").primaryKey(),
  name: text("name").notNull(),
  address: text("address").notNull(),
  city: text("city").notNull(),
  zipCode: text("zip_code").notNull(),
  // Prix mensuel HT (référence de base)
  priceMonthly: decimal("price_monthly", { precision: 10, scale: 2 }).notNull(),
  // Prix trimestriel (3 mois)
  priceQuarterly: decimal("price_quarterly", { precision: 10, scale: 2 }).notNull(),
  // Prix semestriel (6 mois)
  priceSemiannual: decimal("price_semiannual", { precision: 10, scale: 2 }).notNull(),
  // Prix annuel (12 mois)
  priceAnnual: decimal("price_annual", { precision: 10, scale: 2 }).notNull(),
  // Remises en pourcentage
  discountQuarterly: decimal("discount_quarterly", { precision: 5, scale: 2 }).default("0"),
  discountSemiannual: decimal("discount_semiannual", { precision: 5, scale: 2 }).default("0"),
  discountAnnual: decimal("discount_annual", { precision: 5, scale: 2 }).default("0"),
  imageUrl: text("image_url"),
  mapUrl: text("map_url"),
  approvalNumber: text("approval_number"),
});

export const insertCenterSchema = createInsertSchema(centers).pick({
  name: true,
  address: true,
  city: true,
  zipCode: true,
  priceMonthly: true,
  priceQuarterly: true,
  priceSemiannual: true,
  priceAnnual: true,
  discountQuarterly: true,
  discountSemiannual: true,
  discountAnnual: true,
  imageUrl: true,
  mapUrl: true,
  approvalNumber: true,
});

export const centerServices = pgTable("center_services", {
  id: serial("id").primaryKey(),
  centerId: integer("center_id").notNull().references(() => centers.id),
  name: text("name").notNull(),
  included: boolean("included").default(false),
});

export const insertCenterServiceSchema = createInsertSchema(centerServices).pick({
  centerId: true,
  name: true,
  included: true,
});

// Table qui stocke les relations entre les centres et les services annexes
export const centerMailOffers = pgTable("center_mail_offers", {
  id: serial("id").primaryKey(),
  centerId: integer("center_id").notNull().references(() => centers.id),
  mailOfferId: integer("mail_offer_id").notNull().references(() => mailOffers.id),
  // Indique si ce service est disponible dans ce centre
  isAvailable: boolean("is_available").default(true),
});

export const insertCenterMailOfferSchema = createInsertSchema(centerMailOffers).pick({
  centerId: true,
  mailOfferId: true,
  isAvailable: true,
});

export const mailOffers = pgTable("mail_offers", {
  id: serial("id").primaryKey(),
  name: text("name").notNull(),
  description: text("description").notNull(),
  // Le prix peut être 0 pour les services gratuits
  price: decimal("price", { precision: 10, scale: 2 }).notNull().default("0"),
  // Type de service: "mail_scan", "mail_forward", "phone", "meeting_room", "other"
  serviceType: text("service_type").notNull().default("other"),
  // Icône à afficher (identifiant de FontAwesome ou autre bibliothèque d'icônes)
  icon: text("icon"),
  // Caractéristiques du service
  features: jsonb("features").$type<string[]>(),
  // Ordre d'affichage dans la grille
  displayOrder: integer("display_order").default(0),
  // Indique si c'est une option "aucun service" (pour permettre au client de ne rien sélectionner)
  isNoServiceOption: boolean("is_no_service_option").default(false),
  // Options du service avec fréquences et prix correspondants
  frequencies: jsonb("frequencies").$type<{
    id: string;
    name: string;
    description: string;
    price: number;
    isDefault?: boolean;
  }[]>(),
});

export const insertMailOfferSchema = createInsertSchema(mailOffers, {
  frequencies: z.array(z.object({
    id: z.string(),
    name: z.string(),
    description: z.string(),
    price: z.number(),
    isDefault: z.boolean().optional(),
  })).optional(),
}).pick({
  name: true,
  description: true,
  price: true,
  serviceType: true,
  icon: true,
  features: true,
  displayOrder: true,
  isNoServiceOption: true,
  frequencies: true,
});

export const projects = pgTable("projects", {
  id: serial("id").primaryKey(),
  projectTypeId: integer("project_type_id").references(() => projectTypes.id),
  projectSubOptionId: text("project_sub_option_id"), // ID de la sous-option sélectionnée
  firstName: text("first_name"),
  lastName: text("last_name"),
  email: text("email"),
  phone: text("phone"),
  legalStatusId: integer("legal_status_id").references(() => legalStatuses.id),
  centerId: integer("center_id").references(() => centers.id),
  mailOfferId: integer("mail_offer_id").references(() => mailOffers.id),
  selectedFrequency: text("selected_frequency").default("monthly"),
  stripeCustomerId: text("stripe_customer_id"),
  stripeSubscriptionId: text("stripe_subscription_id"),
  status: text("status").default("pending"),
  createdAt: timestamp("created_at").defaultNow(),
});

export const insertProjectSchema = createInsertSchema(projects).pick({
  projectTypeId: true,
  projectSubOptionId: true, // Ajout du champ pour la sous-option
  firstName: true,
  lastName: true,
  email: true,
  phone: true,
  legalStatusId: true,
  centerId: true,
  mailOfferId: true,
  selectedFrequency: true,
  stripeCustomerId: true,
  stripeSubscriptionId: true,
  status: true,
});

export const companyConfig = pgTable("company_config", {
  id: serial("id").primaryKey(),
  name: text("name").notNull(),
  address: text("address").notNull(),
  email: text("email").notNull(),
  phone: text("phone").notNull(),
  website: text("website"),
  legalInformation: text("legal_information"),
  logoUrl: text("logo_url"),
  stripePublicKey: text("stripe_public_key"),
  stripeSecretKey: text("stripe_secret_key"),
  punchline: text("punchline"),
  headerTitle: text("header_title"),
  headerSubtitle: text("header_subtitle"),
  defaultLanguage: text("default_language").default("fr"),
  availableLanguages: jsonb("available_languages").$type<string[]>().default(["fr"]),
  sidebarBanners: jsonb("sidebar_banners").$type<{language: string, imageUrls: string[]}[]>(),
  serviceAdvantages: jsonb("service_advantages").$type<{title: string, description: string, imageUrl: string}[]>(),
  faqUrl: text("faq_url"),
  // Nouvelles options de personnalisation
  themeColors: jsonb("theme_colors").$type<{
    primaryColor: string;
    secondaryColor: string;
    backgroundColor: string;
    textColor: string;
    headerBackgroundColor: string;
    footerBackgroundColor: string;
    buttonColor: string;
    buttonTextColor: string;
    sidebarBackgroundColor: string;
    cardBackgroundColor: string;
  }>(),
  customCSS: text("custom_css"),
});

export const insertCompanyConfigSchema = createInsertSchema(companyConfig).pick({
  name: true,
  address: true,
  email: true,
  phone: true,
  website: true,
  legalInformation: true,
  logoUrl: true,
  stripePublicKey: true,
  stripeSecretKey: true,
  punchline: true,
  headerTitle: true,
  headerSubtitle: true,
  defaultLanguage: true,
  availableLanguages: true,
  sidebarBanners: true,
  serviceAdvantages: true,
  faqUrl: true,
  themeColors: true,
  customCSS: true,
});

export const translations = pgTable("translations", {
  id: serial("id").primaryKey(),
  key: text("key").notNull(),
  language: text("language").notNull(),
  value: text("value").notNull(),
  category: text("category").default("general"),
});

export const insertTranslationSchema = createInsertSchema(translations).pick({
  key: true,
  language: true,
  value: true,
  category: true,
});

// Types
export type User = typeof users.$inferSelect;
export type InsertUser = z.infer<typeof insertUserSchema>;

export type ProjectType = typeof projectTypes.$inferSelect;
export type InsertProjectType = z.infer<typeof insertProjectTypeSchema>;

export type LegalStatus = typeof legalStatuses.$inferSelect;
export type InsertLegalStatus = z.infer<typeof insertLegalStatusSchema>;

export type Center = typeof centers.$inferSelect;
export type InsertCenter = z.infer<typeof insertCenterSchema>;

export type CenterService = typeof centerServices.$inferSelect;
export type InsertCenterService = z.infer<typeof insertCenterServiceSchema>;

export type CenterMailOffer = typeof centerMailOffers.$inferSelect;
export type InsertCenterMailOffer = z.infer<typeof insertCenterMailOfferSchema>;

export type MailOffer = typeof mailOffers.$inferSelect;
export type InsertMailOffer = z.infer<typeof insertMailOfferSchema>;

export type Project = typeof projects.$inferSelect;
export type InsertProject = z.infer<typeof insertProjectSchema>;

export type Translation = typeof translations.$inferSelect;
export type InsertTranslation = z.infer<typeof insertTranslationSchema>;

export type CompanyConfig = typeof companyConfig.$inferSelect;
export type InsertCompanyConfig = z.infer<typeof insertCompanyConfigSchema>;
