import { 
  users, type User, type InsertUser, 
  projectTypes, type ProjectType, type InsertProjectType, 
  legalStatuses, type LegalStatus, type InsertLegalStatus, 
  centers, type Center, type InsertCenter, 
  centerServices, type CenterService, type InsertCenterService,
  centerMailOffers, type CenterMailOffer, type InsertCenterMailOffer,
  mailOffers, type MailOffer, type InsertMailOffer, 
  projects, type Project, type InsertProject, 
  companyConfig, type CompanyConfig, type InsertCompanyConfig,
  translations, type Translation, type InsertTranslation
} from "@shared/schema";

export interface IStorage {
  // Users
  getUser(id: number): Promise<User | undefined>;
  getUserByUsername(username: string): Promise<User | undefined>;
  createUser(user: InsertUser): Promise<User>;
  
  // Project Types
  getAllProjectTypes(): Promise<ProjectType[]>;
  getProjectType(id: number): Promise<ProjectType | undefined>;
  createProjectType(projectType: InsertProjectType): Promise<ProjectType>;
  updateProjectType(id: number, projectType: Partial<InsertProjectType>): Promise<ProjectType | undefined>;
  deleteProjectType(id: number): Promise<boolean>;
  
  // Legal Statuses
  getAllLegalStatuses(): Promise<LegalStatus[]>;
  getLegalStatus(id: number): Promise<LegalStatus | undefined>;
  createLegalStatus(legalStatus: InsertLegalStatus): Promise<LegalStatus>;
  updateLegalStatus(id: number, legalStatus: Partial<InsertLegalStatus>): Promise<LegalStatus | undefined>;
  deleteLegalStatus(id: number): Promise<boolean>;
  
  // Centers
  getAllCenters(): Promise<Center[]>;
  getCenter(id: number): Promise<Center | undefined>;
  createCenter(center: InsertCenter): Promise<Center>;
  updateCenter(id: number, center: Partial<InsertCenter>): Promise<Center | undefined>;
  deleteCenter(id: number): Promise<boolean>;
  
  // Center Services
  getCenterServices(centerId: number): Promise<CenterService[]>;
  getCenterService(id: number): Promise<CenterService | undefined>;
  createCenterService(centerService: InsertCenterService): Promise<CenterService>;
  updateCenterService(id: number, centerService: Partial<InsertCenterService>): Promise<CenterService | undefined>;
  deleteCenterService(id: number): Promise<boolean>;
  
  // Mail Offers
  getAllMailOffers(): Promise<MailOffer[]>;
  getMailOffer(id: number): Promise<MailOffer | undefined>;
  createMailOffer(mailOffer: InsertMailOffer): MailOffer;
  updateMailOffer(id: number, mailOffer: Partial<InsertMailOffer>): Promise<MailOffer | undefined>;
  deleteMailOffer(id: number): Promise<boolean>;
  
  // Center Mail Offers (Relations entre centres et services annexes)
  getCenterMailOffers(centerId: number): Promise<CenterMailOffer[]>;
  getCenterMailOffersByMailOffer(mailOfferId: number): Promise<CenterMailOffer[]>;
  createCenterMailOffer(centerMailOffer: InsertCenterMailOffer): CenterMailOffer;
  updateCenterMailOfferAvailability(centerId: number, mailOfferId: number, isAvailable: boolean): Promise<CenterMailOffer | undefined>;
  deleteCenterMailOffer(centerId: number, mailOfferId: number): Promise<boolean>;
  getCenterAvailableMailOffers(centerId: number): Promise<MailOffer[]>;
  
  // Projects
  getAllProjects(): Promise<Project[]>;
  getProject(id: number): Promise<Project | undefined>;
  getProjectByEmail(email: string): Promise<Project | undefined>;
  createProject(project: InsertProject): Promise<Project>;
  updateProject(id: number, project: Partial<InsertProject>): Promise<Project | undefined>;
  deleteProject(id: number): Promise<boolean>;
  
  // Translations
  getAllTranslations(): Promise<Translation[]>;
  getTranslationsByLanguage(language: string): Promise<Translation[]>;
  getTranslationsByCategory(category: string): Promise<Translation[]>;
  getTranslation(id: number): Promise<Translation | undefined>;
  getTranslationByKey(key: string, language: string): Promise<Translation | undefined>;
  createTranslation(translation: InsertTranslation): Promise<Translation>;
  updateTranslation(id: number, translation: Partial<InsertTranslation>): Promise<Translation | undefined>;
  upsertTranslation(key: string, language: string, value: string, category?: string): Promise<Translation>;
  deleteTranslation(id: number): Promise<boolean>;
  
  // Company Config
  getCompanyConfig(): Promise<CompanyConfig | undefined>;
  updateCompanyConfig(config: InsertCompanyConfig): Promise<CompanyConfig>;
}

export class MemStorage implements IStorage {
  // Translations
  async getAllTranslations(): Promise<Translation[]> {
    return Array.from(this.translations.values());
  }
  
  async getTranslationsByLanguage(language: string): Promise<Translation[]> {
    return Array.from(this.translations.values()).filter(
      (translation) => translation.language === language
    );
  }
  
  async getTranslationsByCategory(category: string): Promise<Translation[]> {
    return Array.from(this.translations.values()).filter(
      (translation) => translation.category === category
    );
  }
  
  async getTranslation(id: number): Promise<Translation | undefined> {
    return this.translations.get(id);
  }
  
  async getTranslationByKey(key: string, language: string): Promise<Translation | undefined> {
    return Array.from(this.translations.values()).find(
      (translation) => translation.key === key && translation.language === language
    );
  }
  
  async createTranslation(insertTranslation: InsertTranslation): Promise<Translation> {
    const id = this.currentTranslationId++;
    const translation: Translation = { ...insertTranslation, id };
    this.translations.set(id, translation);
    return translation;
  }
  
  async updateTranslation(id: number, translation: Partial<InsertTranslation>): Promise<Translation | undefined> {
    const existingTranslation = this.translations.get(id);
    if (!existingTranslation) return undefined;
    
    const updatedTranslation = { ...existingTranslation, ...translation };
    this.translations.set(id, updatedTranslation);
    return updatedTranslation;
  }
  
  async upsertTranslation(key: string, language: string, value: string, category: string = "general"): Promise<Translation> {
    const existingTranslation = await this.getTranslationByKey(key, language);
    
    if (existingTranslation) {
      return this.updateTranslation(existingTranslation.id, { value, category }) as Promise<Translation>;
    } else {
      return this.createTranslation({ key, language, value, category });
    }
  }
  
  async deleteTranslation(id: number): Promise<boolean> {
    return this.translations.delete(id);
  }
  private users: Map<number, User>;
  private projectTypes: Map<number, ProjectType>;
  private legalStatuses: Map<number, LegalStatus>;
  private centers: Map<number, Center>;
  private centerServices: Map<number, CenterService>;
  private centerMailOffers: Map<number, CenterMailOffer>;
  private mailOffers: Map<number, MailOffer>;
  private projects: Map<number, Project>;
  private translations: Map<number, Translation>;
  private companyConfig: CompanyConfig | undefined;
  
  private currentUserId: number;
  private currentProjectTypeId: number;
  private currentLegalStatusId: number;
  private currentCenterId: number;
  private currentCenterServiceId: number;
  private currentCenterMailOfferId: number;
  private currentMailOfferId: number;
  private currentProjectId: number;
  private currentTranslationId: number;
  private currentCompanyConfigId: number;

  constructor() {
    this.users = new Map();
    this.projectTypes = new Map();
    this.legalStatuses = new Map();
    this.centers = new Map();
    this.centerServices = new Map();
    this.centerMailOffers = new Map();
    this.mailOffers = new Map();
    this.projects = new Map();
    this.translations = new Map();
    
    this.currentUserId = 1;
    this.currentProjectTypeId = 1;
    this.currentLegalStatusId = 1;
    this.currentCenterId = 1;
    this.currentCenterServiceId = 1;
    this.currentCenterMailOfferId = 1;
    this.currentMailOfferId = 1;
    this.currentProjectId = 1;
    this.currentTranslationId = 1;
    this.currentCompanyConfigId = 1;
    
    // Insert default data
    this.insertDefaultData();
  }

  // Insert some default data for testing
  private insertDefaultData() {
    // Create an admin user
    this.createUser({
      username: "admin",
      password: "admin123",
      isAdmin: true
    });
    
    // Create project types
    this.createProjectType({
      name: "Domiciliation commerciale",
      description: "Domiciliation de votre société existante ou à créer",
      price: "0",
      hasSubOptions: false,
      subOptions: null
    });
    
    this.createProjectType({
      name: "Domiciliation commerciale avec création d'entreprise",
      description: "Domiciliation de votre société avec sa création",
      price: "0",
      hasSubOptions: true,
      subOptions: [
        {
          id: "creation-societe",
          name: "Création de votre société",
          description: "Service complet d'accompagnement et formalités",
          price: "590"
        },
        {
          id: "creation-auto-entreprise",
          name: "Création de votre auto entreprise",
          description: "Accompagnement pour créer votre auto-entreprise",
          price: "99"
        }
      ]
    });
    
    this.createProjectType({
      name: "Domiciliation commerciale avec transfert",
      description: "Domiciliation de votre société avec son transfert de siège",
      price: "0",
      hasSubOptions: true,
      subOptions: [
        {
          id: "transfert-sans-greffe",
          name: "Transfert de siège sans changement de greffe",
          description: "Transfert dans le même département",
          price: "790"
        },
        {
          id: "transfert-avec-greffe",
          name: "Transfert de siège avec changement de greffe",
          description: "Transfert dans un autre département",
          price: "990"
        }
      ]
    });
    
    // Create legal statuses
    this.createLegalStatus({
      name: "Auto-entrepreneur",
      description: "Statut simplifié pour entrepreneur individuel",
      requiredDocuments: ["Pièce d'identité", "Justificatif de domicile", "Attestation URSSAF"]
    });
    
    this.createLegalStatus({
      name: "SASU",
      description: "Société par Actions Simplifiée Unipersonnelle",
      requiredDocuments: ["Pièce d'identité du dirigeant", "Justificatif de domicile", "Statuts signés", "Kbis"]
    });
    
    this.createLegalStatus({
      name: "EURL",
      description: "Entreprise Unipersonnelle à Responsabilité Limitée",
      requiredDocuments: ["Pièce d'identité du gérant", "Justificatif de domicile", "Statuts signés", "Kbis"]
    });
    
    this.createLegalStatus({
      name: "SAS",
      description: "Société par Actions Simplifiée",
      requiredDocuments: ["Pièce d'identité du président", "Justificatif de domicile", "Statuts signés", "Kbis", "Liste des actionnaires"]
    });
    
    this.createLegalStatus({
      name: "SARL",
      description: "Société à Responsabilité Limitée",
      requiredDocuments: ["Pièce d'identité du gérant", "Justificatif de domicile", "Statuts signés", "Kbis", "PV d'assemblée"]
    });
    
    this.createLegalStatus({
      name: "SCI",
      description: "Société Civile Immobilière",
      requiredDocuments: ["Pièce d'identité du gérant", "Justificatif de domicile", "Statuts signés", "Kbis", "Actes de propriété"]
    });
    
    this.createLegalStatus({
      name: "SA",
      description: "Société Anonyme",
      requiredDocuments: ["Pièce d'identité du président du CA", "Justificatif de domicile", "Statuts signés", "Kbis", "PV du conseil d'administration"]
    });
    
    this.createLegalStatus({
      name: "EI",
      description: "Entreprise Individuelle",
      requiredDocuments: ["Pièce d'identité", "Justificatif de domicile", "Attestation d'inscription au répertoire des métiers ou au RCS"]
    });
    
    this.createLegalStatus({
      name: "Micro-entreprise",
      description: "Régime fiscal simplifié pour très petites entreprises",
      requiredDocuments: ["Pièce d'identité", "Justificatif de domicile", "Attestation URSSAF"]
    });
    
    this.createLegalStatus({
      name: "Association loi 1901",
      description: "Organisation à but non lucratif",
      requiredDocuments: ["Pièce d'identité du président", "Statuts de l'association", "Récépissé de déclaration en préfecture", "Procès-verbal de la dernière assemblée"]
    });
    
    // Create centers
    this.createCenter({
      name: "Centre Marseille Vieux-Port",
      address: "19 rue du Musée",
      city: "Marseille",
      zipCode: "13001",
      priceMonthly: "19",
      priceQuarterly: "57",
      priceSemiannual: "108",
      priceAnnual: "204",
      discountQuarterly: "0",
      discountSemiannual: "5.26",
      discountAnnual: "10.53",
      imageUrl: "https://images.unsplash.com/photo-1558386620-6b5048d3cc04?auto=format&fit=crop&w=600&q=80",
      mapUrl: "https://maps.google.com/?q=19+rue+du+Musée+Marseille",
      approvalNumber: "2023/AEDFJ/13/05"
    });
    
    this.createCenter({
      name: "Centre Marseille Belle de Mai",
      address: "40 rue Belle de Mai",
      city: "Marseille",
      zipCode: "13003",
      priceMonthly: "19",
      priceQuarterly: "57",
      priceSemiannual: "108",
      priceAnnual: "204",
      discountQuarterly: "0",
      discountSemiannual: "5.26",
      discountAnnual: "10.53",
      imageUrl: "https://images.unsplash.com/photo-1542744095-0d53267d2bdd?auto=format&fit=crop&w=600&q=80",
      mapUrl: "https://maps.google.com/?q=40+rue+Belle+de+Mai+Marseille",
      approvalNumber: "2023/BDJSN/13/21"
    });
    
    this.createCenter({
      name: "Centre Marseille Saint-Pierre",
      address: "209 rue Saint-Pierre",
      city: "Marseille",
      zipCode: "13005",
      priceMonthly: "29",
      priceQuarterly: "87",
      priceSemiannual: "162",
      priceAnnual: "300",
      discountQuarterly: "0",
      discountSemiannual: "6.90",
      discountAnnual: "13.79",
      imageUrl: "https://images.unsplash.com/photo-1561518776-e76a5e48f731?auto=format&fit=crop&w=600&q=80",
      mapUrl: "https://maps.google.com/?q=209+rue+Saint-Pierre+Marseille",
      approvalNumber: "2023/CDFHT/13/33"
    });
    
    this.createCenter({
      name: "Centre Marseille Catalans",
      address: "97 rue Sauveur Tobelem",
      city: "Marseille",
      zipCode: "13007",
      priceMonthly: "29",
      priceQuarterly: "87",
      priceSemiannual: "162",
      priceAnnual: "300",
      discountQuarterly: "0",
      discountSemiannual: "6.90",
      discountAnnual: "13.79",
      imageUrl: "https://images.unsplash.com/photo-1568736772245-26914aae0b09?auto=format&fit=crop&w=600&q=80",
      mapUrl: "https://maps.google.com/?q=97+rue+Sauveur+Tobelem+Marseille",
      approvalNumber: "2023/ESDLN/13/45"
    });
    
    // Create center services for all centers
    // Centre 1 - Vieux-Port
    this.createCenterService({
      centerId: 1,
      name: "Réception du courrier",
      included: true
    });
    
    // Centre 2 - Belle de Mai
    this.createCenterService({
      centerId: 2,
      name: "Réception du courrier",
      included: true
    });
    
    // Centre 3 - Saint-Pierre
    this.createCenterService({
      centerId: 3,
      name: "Réception du courrier",
      included: true
    });
    
    // Centre 4 - Catalans
    this.createCenterService({
      centerId: 4,
      name: "Réception du courrier",
      included: true
    });
    
    // Create annex services (mail offers used for this purpose)
    const mailScan = this.createMailOffer({
      name: "NUMÉRISATION COURRIER",
      description: "Recevez vos documents importants rapidement et en toute sécurité, directement dans votre boîte mail.",
      price: "19",
      icon: "fa-file-pdf",
      serviceType: "mail_scan",
      features: ["Numérisation des courriers importants", "Transmission par email", "Archivage électronique"],
      frequencies: [
        {
          id: "monthly",
          name: "Mensuel",
          description: "Paiement mensuel",
          price: 19,
          isDefault: true
        },
        {
          id: "quarterly",
          name: "Trimestriel",
          description: "Paiement tous les 3 mois",
          price: 57
        },
        {
          id: "semiannual",
          name: "Semestriel",
          description: "Paiement tous les 6 mois",
          price: 108
        },
        {
          id: "annual",
          name: "Annuel",
          description: "Paiement annuel",
          price: 204
        }
      ]
    });
    
    const mailForward = this.createMailOffer({
      name: "RÉEXPÉDITION POSTALE",
      description: "Assurez une continuité sans faille de vos communications postales, où que vous soyez.",
      price: "9",
      icon: "fa-paper-plane",
      serviceType: "mail_forward",
      features: ["Acheminement de votre courrier", "Suivi des expéditions", "Service rapide et fiable"],
      frequencies: [
        {
          id: "biweekly",
          name: "Tous les 15 jours",
          description: "Réexpédition bimensuelle",
          price: 9,
          isDefault: true
        },
        {
          id: "weekly",
          name: "Chaque semaine",
          description: "Réexpédition hebdomadaire",
          price: 15
        }
      ]
    });
    
    const phoneService = this.createMailOffer({
      name: "LIGNE FIXE PERSONNALISÉE",
      description: "Établissez une présence professionnelle avec une ligne téléphonique fixe dédiée.",
      price: "15",
      icon: "fa-phone",
      serviceType: "phone",
      features: ["Numéro professionnel dédié", "Accueil téléphonique", "Image professionnelle renforcée"],
      frequencies: [
        {
          id: "voicemail",
          name: "Avec messagerie vocale",
          description: "Messagerie vocale personnalisée",
          price: 15,
          isDefault: true
        },
        {
          id: "call_transfer",
          name: "Avec transfert d'appels",
          description: "Transfert vers votre mobile",
          price: 39
        }
      ]
    });
    
    const smsService = this.createMailOffer({
      name: "NOTIFICATION PAR SMS",
      description: "Soyez alerté immédiatement dès réception de vos courriers importants.",
      price: "5",
      icon: "fa-mobile-alt",
      serviceType: "sms",
      features: ["Alerte SMS instantanée", "Notification en temps réel", "Suivi efficace de vos courriers"],
      frequencies: [
        {
          id: "immediate",
          name: "Dès réception",
          description: "Notification immédiate",
          price: 5,
          isDefault: true
        }
      ]
    });
    
    // Set up the relationships between centers and mail offers
    // By default, all services are available at all centers
    for (let centerId = 1; centerId <= 4; centerId++) {
      // Numérisation courrier disponible dans tous les centres
      this.createCenterMailOffer({
        centerId,
        mailOfferId: mailScan.id,
        isAvailable: true
      });
      
      // Réexpédition postale disponible dans tous les centres
      this.createCenterMailOffer({
        centerId,
        mailOfferId: mailForward.id,
        isAvailable: true
      });
      
      // Ligne fixe disponible dans tous les centres
      this.createCenterMailOffer({
        centerId,
        mailOfferId: phoneService.id,
        isAvailable: true
      });
      
      // Service SMS disponible dans tous les centres
      this.createCenterMailOffer({
        centerId,
        mailOfferId: smsService.id,
        isAvailable: true
      });
    }
    
    // Create company config
    this.updateCompanyConfig({
      name: "DOMICILIATION MARSEILLE",
      address: "123 Avenue de la République, 13001 Marseille",
      email: "contact@domiciliation-marseille.fr",
      phone: "04 91 00 00 00",
      website: "www.domiciliation-marseille.fr",
      legalInformation: "SARL au capital de 10 000€ - RCS Marseille 123456789",
      logoUrl: "https://domiciliationmarseille.fr/wp-content/uploads/2024/07/logo_dcm_whitev2.png.webp",
      stripePublicKey: "",
      stripeSecretKey: "",
      punchline: "+50 000 entrepreneurs nous font confiance !",
      headerTitle: "Créez votre projet de domiciliation",
      headerSubtitle: "Suivez notre processus guidé en 7 étapes pour obtenir votre adresse professionnelle à Marseille",
      defaultLanguage: "fr",
      availableLanguages: ["fr", "en"],
      sidebarBanners: [
        {
          language: "fr",
          imageUrls: [
            "https://images.unsplash.com/photo-1490642914619-7955a3fd483c?w=600&auto=format&fit=crop&q=80",
            "https://images.unsplash.com/photo-1538689621163-f5be0ad13ec7?w=600&auto=format&fit=crop&q=80"
          ]
        },
        {
          language: "en",
          imageUrls: [
            "https://images.unsplash.com/photo-1577358961783-0effef9530d8?w=600&auto=format&fit=crop&q=80",
            "https://images.unsplash.com/photo-1571989569744-4bfa1e7e1186?w=600&auto=format&fit=crop&q=80"
          ]
        }
      ],
      themeColors: {
        primaryColor: "#0070F3",
        secondaryColor: "#000000",
        backgroundColor: "#FAFAFA",
        textColor: "#333333",
        headerBackgroundColor: "#123c63",
        footerBackgroundColor: "#F5F5F7",
        buttonColor: "#0070F3",
        buttonTextColor: "#FFFFFF",
        sidebarBackgroundColor: "#FFFFFF",
        cardBackgroundColor: "#FFFFFF"
      },
      customCSS: ""
    });
  }

  // Users
  async getUser(id: number): Promise<User | undefined> {
    return this.users.get(id);
  }

  async getUserByUsername(username: string): Promise<User | undefined> {
    return Array.from(this.users.values()).find(
      (user) => user.username === username,
    );
  }

  async createUser(insertUser: InsertUser): Promise<User> {
    const id = this.currentUserId++;
    const user: User = { ...insertUser, id };
    this.users.set(id, user);
    return user;
  }
  
  // Project Types
  async getAllProjectTypes(): Promise<ProjectType[]> {
    return Array.from(this.projectTypes.values());
  }
  
  async getProjectType(id: number): Promise<ProjectType | undefined> {
    return this.projectTypes.get(id);
  }
  
  async createProjectType(insertProjectType: InsertProjectType): Promise<ProjectType> {
    const id = this.currentProjectTypeId++;
    const projectType: ProjectType = { ...insertProjectType, id };
    this.projectTypes.set(id, projectType);
    return projectType;
  }
  
  async updateProjectType(id: number, projectType: Partial<InsertProjectType>): Promise<ProjectType | undefined> {
    const existingProjectType = this.projectTypes.get(id);
    if (!existingProjectType) return undefined;
    
    const updatedProjectType = { ...existingProjectType, ...projectType };
    this.projectTypes.set(id, updatedProjectType);
    return updatedProjectType;
  }
  
  async deleteProjectType(id: number): Promise<boolean> {
    return this.projectTypes.delete(id);
  }
  
  // Legal Statuses
  async getAllLegalStatuses(): Promise<LegalStatus[]> {
    return Array.from(this.legalStatuses.values());
  }
  
  async getLegalStatus(id: number): Promise<LegalStatus | undefined> {
    return this.legalStatuses.get(id);
  }
  
  async createLegalStatus(insertLegalStatus: InsertLegalStatus): Promise<LegalStatus> {
    const id = this.currentLegalStatusId++;
    const legalStatus: LegalStatus = { ...insertLegalStatus, id };
    this.legalStatuses.set(id, legalStatus);
    return legalStatus;
  }
  
  async updateLegalStatus(id: number, legalStatus: Partial<InsertLegalStatus>): Promise<LegalStatus | undefined> {
    const existingLegalStatus = this.legalStatuses.get(id);
    if (!existingLegalStatus) return undefined;
    
    const updatedLegalStatus = { ...existingLegalStatus, ...legalStatus };
    this.legalStatuses.set(id, updatedLegalStatus);
    return updatedLegalStatus;
  }
  
  async deleteLegalStatus(id: number): Promise<boolean> {
    return this.legalStatuses.delete(id);
  }
  
  // Centers
  async getAllCenters(): Promise<Center[]> {
    return Array.from(this.centers.values());
  }
  
  async getCenter(id: number): Promise<Center | undefined> {
    return this.centers.get(id);
  }
  
  async createCenter(insertCenter: InsertCenter): Promise<Center> {
    const id = this.currentCenterId++;
    const center: Center = { ...insertCenter, id };
    this.centers.set(id, center);
    return center;
  }
  
  async updateCenter(id: number, center: Partial<InsertCenter>): Promise<Center | undefined> {
    const existingCenter = this.centers.get(id);
    if (!existingCenter) return undefined;
    
    const updatedCenter = { ...existingCenter, ...center };
    this.centers.set(id, updatedCenter);
    return updatedCenter;
  }
  
  async deleteCenter(id: number): Promise<boolean> {
    return this.centers.delete(id);
  }
  
  // Center Services
  async getCenterServices(centerId: number): Promise<CenterService[]> {
    return Array.from(this.centerServices.values()).filter(
      (service) => service.centerId === centerId
    );
  }
  
  async getCenterService(id: number): Promise<CenterService | undefined> {
    return this.centerServices.get(id);
  }
  
  async createCenterService(insertCenterService: InsertCenterService): Promise<CenterService> {
    const id = this.currentCenterServiceId++;
    const centerService: CenterService = { ...insertCenterService, id };
    this.centerServices.set(id, centerService);
    return centerService;
  }
  
  async updateCenterService(id: number, centerService: Partial<InsertCenterService>): Promise<CenterService | undefined> {
    const existingCenterService = this.centerServices.get(id);
    if (!existingCenterService) return undefined;
    
    const updatedCenterService = { ...existingCenterService, ...centerService };
    this.centerServices.set(id, updatedCenterService);
    return updatedCenterService;
  }
  
  async deleteCenterService(id: number): Promise<boolean> {
    return this.centerServices.delete(id);
  }
  
  // Mail Offers
  async getAllMailOffers(): Promise<MailOffer[]> {
    return Array.from(this.mailOffers.values());
  }
  
  async getMailOffer(id: number): Promise<MailOffer | undefined> {
    return this.mailOffers.get(id);
  }
  
  createMailOffer(insertMailOffer: InsertMailOffer): MailOffer {
    const id = this.currentMailOfferId++;
    const mailOffer: MailOffer = { ...insertMailOffer, id };
    this.mailOffers.set(id, mailOffer);
    return mailOffer;
  }
  
  async updateMailOffer(id: number, mailOffer: Partial<InsertMailOffer>): Promise<MailOffer | undefined> {
    const existingMailOffer = this.mailOffers.get(id);
    if (!existingMailOffer) return undefined;
    
    const updatedMailOffer = { ...existingMailOffer, ...mailOffer };
    this.mailOffers.set(id, updatedMailOffer);
    return updatedMailOffer;
  }
  
  async deleteMailOffer(id: number): Promise<boolean> {
    return this.mailOffers.delete(id);
  }
  
  // Center Mail Offers
  async getCenterMailOffers(centerId: number): Promise<CenterMailOffer[]> {
    return Array.from(this.centerMailOffers.values()).filter(
      (centerMailOffer) => centerMailOffer.centerId === centerId
    );
  }
  
  async getCenterMailOffersByMailOffer(mailOfferId: number): Promise<CenterMailOffer[]> {
    return Array.from(this.centerMailOffers.values()).filter(
      (centerMailOffer) => centerMailOffer.mailOfferId === mailOfferId
    );
  }
  
  createCenterMailOffer(insertCenterMailOffer: InsertCenterMailOffer): CenterMailOffer {
    const id = this.currentCenterMailOfferId++;
    const centerMailOffer: CenterMailOffer = { ...insertCenterMailOffer, id };
    this.centerMailOffers.set(id, centerMailOffer);
    return centerMailOffer;
  }
  
  async updateCenterMailOfferAvailability(centerId: number, mailOfferId: number, isAvailable: boolean): Promise<CenterMailOffer | undefined> {
    const centerMailOffer = Array.from(this.centerMailOffers.values()).find(
      (cmo) => cmo.centerId === centerId && cmo.mailOfferId === mailOfferId
    );
    
    if (!centerMailOffer) {
      // If the relation doesn't exist yet, create it
      return this.createCenterMailOffer({
        centerId,
        mailOfferId,
        isAvailable
      });
    }
    
    // Update the existing relation
    const updatedCenterMailOffer = { ...centerMailOffer, isAvailable };
    this.centerMailOffers.set(centerMailOffer.id, updatedCenterMailOffer);
    return updatedCenterMailOffer;
  }
  
  async deleteCenterMailOffer(centerId: number, mailOfferId: number): Promise<boolean> {
    const centerMailOffer = Array.from(this.centerMailOffers.values()).find(
      (cmo) => cmo.centerId === centerId && cmo.mailOfferId === mailOfferId
    );
    
    if (!centerMailOffer) {
      return false;
    }
    
    return this.centerMailOffers.delete(centerMailOffer.id);
  }
  
  async getCenterAvailableMailOffers(centerId: number): Promise<MailOffer[]> {
    // Récupérer les relations centre-service qui sont disponibles pour ce centre
    const centerMailOffers = Array.from(this.centerMailOffers.values())
      .filter(cmo => cmo.centerId === centerId && cmo.isAvailable);
      
    // Récupérer les IDs des services annexes disponibles
    const availableMailOfferIds = centerMailOffers.map(cmo => cmo.mailOfferId);
    
    console.log('Available mail offer IDs:', availableMailOfferIds);
    
    // Récupérer tous les services annexes disponibles pour ce centre
    return Array.from(this.mailOffers.values()).filter(
      mailOffer => availableMailOfferIds.includes(mailOffer.id)
    );
  }
  
  // Projects
  async getAllProjects(): Promise<Project[]> {
    return Array.from(this.projects.values());
  }
  
  async getProject(id: number): Promise<Project | undefined> {
    return this.projects.get(id);
  }
  
  async getProjectByEmail(email: string): Promise<Project | undefined> {
    return Array.from(this.projects.values()).find(
      (project) => project.email === email
    );
  }
  
  async createProject(insertProject: InsertProject): Promise<Project> {
    const id = this.currentProjectId++;
    const now = new Date();
    const project: Project = { 
      ...insertProject, 
      id,
      createdAt: now,
      projectSubOptionId: insertProject.projectSubOptionId || null
    };
    this.projects.set(id, project);
    return project;
  }
  
  async updateProject(id: number, project: Partial<InsertProject>): Promise<Project | undefined> {
    const existingProject = this.projects.get(id);
    if (!existingProject) return undefined;
    
    const updatedProject = { ...existingProject, ...project };
    this.projects.set(id, updatedProject);
    return updatedProject;
  }
  
  async deleteProject(id: number): Promise<boolean> {
    return this.projects.delete(id);
  }
  
  // Company Config
  async getCompanyConfig(): Promise<CompanyConfig | undefined> {
    return this.companyConfig;
  }
  
  async updateCompanyConfig(config: InsertCompanyConfig): Promise<CompanyConfig> {
    if (this.companyConfig) {
      this.companyConfig = { ...this.companyConfig, ...config };
    } else {
      const id = this.currentCompanyConfigId++;
      this.companyConfig = { ...config, id };
    }
    return this.companyConfig;
  }
}

export const storage = new MemStorage();
