import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface VisitSlot extends RowDataPacket {
  id: number;
  property_id: number;
  slot_date: string;
  start_time: string;
  end_time: string;
  status: 'AVAILABLE' | 'BOOKED' | 'UNAVAILABLE';
  created_at: string;
  updated_at: string;
}

export const findAll = async (connection?: any): Promise<any[]> => {
  const db = connection || pool;
  const query = `
    SELECT vs.*, p.title as property_title, p.reference as property_reference
    FROM visit_slots vs
    JOIN properties p ON p.id = vs.property_id
    ORDER BY vs.slot_date DESC, vs.start_time ASC
  `;
  const [rows] = await db.query(query);
  return rows;
};

export const findAllForProperty = async (propertyId: number, includeUnavailable = false, connection?: any): Promise<VisitSlot[]> => {
  const db = connection || pool;
  let query = 'SELECT * FROM visit_slots WHERE property_id = ?';
  const params: any[] = [propertyId];
  if (!includeUnavailable) {
    query += ' AND status = "AVAILABLE"';
  }
  query += ' ORDER BY slot_date ASC, start_time ASC';
  const [rows] = await db.query(query, params);
  return rows;
};

export const findById = async (id: number, connection?: any): Promise<VisitSlot | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM visit_slots WHERE id = ?', [id]);
  return rows[0] || null;
};

export const findByIdForUpdate = async (id: number, connection: any): Promise<VisitSlot | null> => {
  const [rows] = await connection.query('SELECT * FROM visit_slots WHERE id = ? FOR UPDATE', [id]);
  return rows[0] || null;
};

export const create = async (propertyId: number, data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  const query = 'INSERT INTO visit_slots (property_id, slot_date, start_time, end_time) VALUES (?, ?, ?, ?)';
  const [result] = await db.query(query, [propertyId, data.slot_date, data.start_time, data.end_time]);
  return (result as ResultSetHeader).insertId;
};

export const update = async (id: number, data: any, connection?: any): Promise<void> => {
  const db = connection || pool;
  const updates: string[] = [];
  const params: any[] = [];
  
  for (const [key, value] of Object.entries(data)) {
    if (value !== undefined) {
      updates.push(`${key} = ?`);
      params.push(value);
    }
  }
  
  if (updates.length > 0) {
    params.push(id);
    await db.query(`UPDATE visit_slots SET ${updates.join(', ')} WHERE id = ?`, params);
  }
};

export const deleteById = async (id: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await db.query('DELETE FROM visit_slots WHERE id = ?', [id]);
};

export const createBatch = async (slots: { property_id: number; slot_date: string; start_time: string; end_time: string }[], connection?: any): Promise<number> => {
  const db = connection || pool;
  let count = 0;
  for (const slot of slots) {
    try {
      await db.query(
        'INSERT IGNORE INTO visit_slots (property_id, slot_date, start_time, end_time) VALUES (?, ?, ?, ?)',
        [slot.property_id, slot.slot_date, slot.start_time, slot.end_time]
      );
      count++;
    } catch (e) {
      // Ignore duplicate entries
    }
  }
  return count;
};
