import { pool } from '../config/database';
import * as visitSlotsRepo from '../repositories/visitSlots.repository';
import * as visitRequestsRepo from '../repositories/visitRequests.repository';
import * as propertiesRepo from '../repositories/properties.repository';
import * as auditRepo from '../repositories/audit.repository';

// ==============================
// SLOTS
// ==============================

export const getAllVisitSlots = async () => {
  return await visitSlotsRepo.findAll();
};

export const getVisitSlotsForProperty = async (propertyId: number, includeUnavailable = false) => {
  return await visitSlotsRepo.findAllForProperty(propertyId, includeUnavailable);
};

export interface ScheduleSlotConfig {
  start_time: string;
  end_time: string;
}

export type DayOfWeekKey = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday';

export interface DayScheduleConfig {
  enabled?: boolean;
  slots?: ScheduleSlotConfig[];
}

export interface BatchSchedulesConfig {
  days?: Partial<Record<DayOfWeekKey, DayScheduleConfig>>;
  monday?: DayScheduleConfig;
  tuesday?: DayScheduleConfig;
  wednesday?: DayScheduleConfig;
  thursday?: DayScheduleConfig;
  friday?: DayScheduleConfig;
  saturday?: DayScheduleConfig;
  sunday?: DayScheduleConfig;
  mon_thu?: {
    enabled?: boolean;
    slots?: ScheduleSlotConfig[];
  };
}

export const createVisitSlot = async (
  propertyId: number | string,
  data: any,
  userId: number,
  ip: string,
  userAgent?: string
) => {
  if (propertyId === 'ALL' || propertyId === 'all' || propertyId === 0) {
    const [propertiesRows] = await pool.query(
      "SELECT id FROM properties WHERE property_status != 'ARCHIVED'"
    );
    const properties = propertiesRows as any[];
    if (properties.length === 0) throw new Error('Aucun bien immobilier actif trouvé');

    const slotsToCreate = properties.map((p) => ({
      property_id: p.id,
      slot_date: data.slot_date,
      start_time: data.start_time,
      end_time: data.end_time,
    }));
    const createdCount = await visitSlotsRepo.createBatch(slotsToCreate);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'CREATE',
      entity_type: 'VISIT_SLOT_ALL',
      entity_id: null,
      old_values: null,
      new_values: { ...data, createdCount, propertiesCount: properties.length },
      ip_address: ip,
      user_agent: userAgent,
    });

    return { allProperties: true, createdCount, propertiesCount: properties.length, ...data };
  }

  const numericPropertyId = typeof propertyId === 'string' ? parseInt(propertyId) : propertyId;
  const property = await propertiesRepo.findById(numericPropertyId);
  if (!property) throw new Error('Bien introuvable');

  try {
    const id = await visitSlotsRepo.create(numericPropertyId, data);
    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'CREATE',
      entity_type: 'VISIT_SLOT',
      entity_id: id,
      old_values: null,
      new_values: data,
      ip_address: ip,
      user_agent: userAgent
    });
    return { id, ...data };
  } catch (error: any) {
    if (error.code === 'ER_DUP_ENTRY') throw new Error('Un créneau existe déjà pour cette date et heure');
    throw error;
  }
};

export const generateWeekdaysVisitSlots = async (
  propertyId: number | string,
  startDateStr: string,
  weeksCount: number,
  userId: number,
  ip: string,
  userAgent?: string,
  schedules?: BatchSchedulesConfig
) => {
  let targetPropertyIds: number[] = [];
  const isAll = propertyId === 'ALL' || propertyId === 'all' || propertyId === 0 || !propertyId;

  if (isAll) {
    const [propertiesRows] = await pool.query(
      "SELECT id FROM properties WHERE property_status != 'ARCHIVED'"
    );
    const properties = propertiesRows as any[];
    if (properties.length === 0) throw new Error('Aucun bien immobilier actif trouvé');
    targetPropertyIds = properties.map((p) => p.id);
  } else {
    const numericPropertyId = typeof propertyId === 'string' ? parseInt(propertyId) : propertyId;
    const property = await propertiesRepo.findById(numericPropertyId);
    if (!property) throw new Error('Bien introuvable');
    targetPropertyIds = [numericPropertyId];
  }

  // 1. Horaires du Lundi au Jeudi (Du lundi au jeudi)
  const monThuConfig = {
    enabled: schedules?.mon_thu?.enabled !== false,
    slots: schedules?.mon_thu?.slots && schedules.mon_thu.slots.length > 0
      ? schedules.mon_thu.slots
      : [
          { start_time: '10:00', end_time: '13:00' },
          { start_time: '14:30', end_time: '17:00' },
        ],
  };

  // 2. Horaires du Vendredi (Vendredi a des créneaux différents)
  const friConfig = {
    enabled: schedules?.friday?.enabled !== false,
    slots: schedules?.friday?.slots && schedules.friday.slots.length > 0
      ? schedules.friday.slots
      : [
          { start_time: '09:30', end_time: '12:30' },
          { start_time: '15:00', end_time: '18:00' },
        ],
  };

  // 3. Horaires du Samedi (Samedi a des créneaux différents)
  const satConfig = {
    enabled: schedules?.saturday?.enabled !== false,
    slots: schedules?.saturday?.slots && schedules.saturday.slots.length > 0
      ? schedules.saturday.slots
      : [
          { start_time: '09:30', end_time: '13:30' },
        ],
  };

  const slotsToCreate: { property_id: number; slot_date: string; start_time: string; end_time: string }[] = [];
  const startDate = new Date(startDateStr);
  const totalDays = weeksCount * 7;

  const dayKeyByIndex: Record<number, DayOfWeekKey> = {
    0: 'sunday',
    1: 'monday',
    2: 'tuesday',
    3: 'wednesday',
    4: 'thursday',
    5: 'friday',
    6: 'saturday',
  };

  for (let i = 0; i < totalDays; i++) {
    const d = new Date(startDate);
    d.setDate(startDate.getDate() + i);

    const dayOfWeek = d.getDay(); // 0 = Sun, 1 = Mon, ..., 5 = Fri, 6 = Sat
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const dateStr = `${year}-${month}-${day}`;

    const dayKey = dayKeyByIndex[dayOfWeek];
    const specificDayConfig = schedules?.days?.[dayKey] || (schedules as any)?.[dayKey];

    let daySlots: ScheduleSlotConfig[] = [];

    // Priorité à la configuration par jour individuel si fournie
    if (specificDayConfig !== undefined) {
      if (specificDayConfig.enabled && Array.isArray(specificDayConfig.slots) && specificDayConfig.slots.length > 0) {
        daySlots = specificDayConfig.slots;
      }
    } else {
      // Du Lundi au Jeudi (1, 2, 3, 4)
      if (dayOfWeek >= 1 && dayOfWeek <= 4 && monThuConfig.enabled) {
        daySlots = monThuConfig.slots;
      }
      // Vendredi (5)
      else if (dayOfWeek === 5 && friConfig.enabled) {
        daySlots = friConfig.slots;
      }
      // Samedi (6)
      else if (dayOfWeek === 6 && satConfig.enabled) {
        daySlots = satConfig.slots;
      }
    }

    if (daySlots.length > 0) {
      for (const pId of targetPropertyIds) {
        for (const slot of daySlots) {
          slotsToCreate.push({
            property_id: pId,
            slot_date: dateStr,
            start_time: slot.start_time,
            end_time: slot.end_time,
          });
        }
      }
    }
  }

  const createdCount = await visitSlotsRepo.createBatch(slotsToCreate);

  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'CREATE',
    entity_type: isAll ? 'VISIT_SLOT_BATCH_ALL' : 'VISIT_SLOT_BATCH',
    entity_id: isAll ? null : targetPropertyIds[0],
    old_values: null,
    new_values: {
      isAll,
      propertiesCount: targetPropertyIds.length,
      startDateStr,
      weeksCount,
      createdCount,
      monThuConfig,
      friConfig,
      satConfig,
    },
    ip_address: ip,
    user_agent: userAgent,
  });

  return {
    createdCount,
    totalGenerated: slotsToCreate.length,
    propertiesCount: targetPropertyIds.length,
    isAllProperties: isAll,
  };
};


export const updateVisitSlot = async (id: number, data: any, userId: number, ip: string, userAgent?: string) => {
  const slot = await visitSlotsRepo.findById(id);
  if (!slot) throw new Error('Créneau introuvable');

  await visitSlotsRepo.update(id, data);
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'UPDATE',
    entity_type: 'VISIT_SLOT',
    entity_id: id,
    old_values: slot,
    new_values: { ...slot, ...data },
    ip_address: ip,
    user_agent: userAgent
  });
};

export const updateVisitSlotStatus = async (id: number, status: string, userId: number, ip: string, userAgent?: string) => {
  const slot = await visitSlotsRepo.findById(id);
  if (!slot) throw new Error('Créneau introuvable');

  await visitSlotsRepo.update(id, { status });
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'UPDATE_STATUS',
    entity_type: 'VISIT_SLOT',
    entity_id: id,
    old_values: { status: slot.status },
    new_values: { status },
    ip_address: ip,
    user_agent: userAgent
  });
};

export const deleteVisitSlot = async (id: number, userId: number, ip: string, userAgent?: string) => {
  const slot = await visitSlotsRepo.findById(id);
  if (!slot) throw new Error('Créneau introuvable');
  if (slot.status === 'BOOKED') throw new Error('Impossible de supprimer un créneau réservé');

  await visitSlotsRepo.deleteById(id);
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'DELETE',
    entity_type: 'VISIT_SLOT',
    entity_id: id,
    old_values: slot,
    new_values: null,
    ip_address: ip,
    user_agent: userAgent
  });
};

// ==============================
// REQUESTS
// ==============================

export const getVisitRequests = async () => {
  return await visitRequestsRepo.findAll();
};

export const getVisitRequestById = async (id: number) => {
  return await visitRequestsRepo.findById(id);
};

export const createVisitRequest = async (data: any, userId: number | null, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const slot = await visitSlotsRepo.findByIdForUpdate(data.visit_slot_id, connection);
    if (!slot) throw new Error('Créneau introuvable');
    if (slot.status !== 'AVAILABLE') throw new Error('Ce créneau n\'est plus disponible');

    const requestId = await visitRequestsRepo.create({ ...data, user_id: userId, status: 'NEW' }, connection);

    // Notify staff (including agents)
    const notificationsService = await import('./notifications.service');
    const { sendExternalNotification } = await import('./notificationSender.service');
    
    // Add WhatsApp click-to-chat info
    const whatsappMsg = encodeURIComponent(`Bonjour ${data.first_name || ''}, suite à votre demande de visite pour le bien...`);
    const whatsappLink = `https://wa.me/${data.phone?.replace(/[^0-9]/g, '')}?text=${whatsappMsg}`;

    await notificationsService.notifyStaff(
      'VISIT',
      'Nouvelle demande de visite',
      `Une nouvelle demande de visite a été planifiée pour le bien (ID: ${data.property_id || 'N/A'}).\n<a href="${whatsappLink}" target="_blank" class="text-green-600 hover:underline">Contacter par WhatsApp</a>`,
      true, // Include agents
      connection
    );

    // Réserver immédiatement le créneau pour qu'il ne soit plus disponible
    await visitSlotsRepo.update(data.visit_slot_id, { status: 'BOOKED' }, connection);
    
    await connection.commit();

    setImmediate(async () => {
      try {
        await sendExternalNotification('VISIT', data);
      } catch (err) {
        console.error('Erreur lors de l\'envoi de la notification de visite:', err);
      }
    });

    return { id: requestId, ...data };
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const updateVisitRequestStatus = async (id: number, status: string, userId: number, ip: string, userAgent?: string) => {
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();

    const request = await visitRequestsRepo.findById(id, connection);
    if (!request) throw new Error('Demande introuvable');

    if (status === 'CANCELLED' || status === 'RESCHEDULED') {
      // Liberate the slot if the request is cancelled or rescheduled
      if (request.visit_slot_id && !['CANCELLED', 'RESCHEDULED'].includes(request.status)) {
        await visitSlotsRepo.update(request.visit_slot_id, { status: 'AVAILABLE' }, connection);
      }
    } else if (['CANCELLED', 'RESCHEDULED'].includes(request.status) && ['NEW', 'PENDING', 'CONFIRMED'].includes(status)) {
      // If bringing back a cancelled request to active status, we must book the slot again
      if (!request.visit_slot_id) throw new Error('Aucun créneau associé');
      const slot = await visitSlotsRepo.findByIdForUpdate(request.visit_slot_id, connection);
      if (!slot) throw new Error('Créneau introuvable');
      if (slot.status !== 'AVAILABLE') throw new Error('Le créneau n\'est plus disponible (déjà réservé par ailleurs)');

      await visitSlotsRepo.update(slot.id, { status: 'BOOKED' }, connection);
    }

    await visitRequestsRepo.update(id, { status }, connection);

    await auditRepo.createAuditLog({
      user_id: userId,
      action: 'UPDATE_STATUS',
      entity_type: 'VISIT_REQUEST',
      entity_id: id,
      old_values: { status: request.status },
      new_values: { status },
      ip_address: ip,
      user_agent: userAgent
    }, connection);

    await connection.commit();
  } catch (error) {
    await connection.rollback();
    throw error;
  } finally {
    connection.release();
  }
};

export const assignVisitRequest = async (id: number, assigned_agent_id: number | null, userId: number, ip: string, userAgent?: string) => {
  const request = await visitRequestsRepo.findById(id);
  if (!request) throw new Error('Demande introuvable');

  await visitRequestsRepo.update(id, { assigned_agent_id });
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'ASSIGN',
    entity_type: 'VISIT_REQUEST',
    entity_id: id,
    old_values: { assigned_agent_id: request.assigned_agent_id },
    new_values: { assigned_agent_id },
    ip_address: ip,
    user_agent: userAgent
  });
};

export const addNoteToVisitRequest = async (id: number, admin_notes: string | null, userId: number, ip: string, userAgent?: string) => {
  const request = await visitRequestsRepo.findById(id);
  if (!request) throw new Error('Demande introuvable');

  await visitRequestsRepo.update(id, { admin_notes });
  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'ADD_NOTE',
    entity_type: 'VISIT_REQUEST',
    entity_id: id,
    old_values: { admin_notes: request.admin_notes },
    new_values: { admin_notes },
    ip_address: ip,
    user_agent: userAgent
  });
};
