import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface ResidenceUnitType extends RowDataPacket {
  id: number;
  residence_project_id: number;
  code: string;
  name: string;
  surface: number;
  founder_price: number;
  public_price: number;
  parking_available: boolean;
  description: string | null;
  plan_image_url: string | null;
  created_at: Date;
  updated_at: Date;
}

export const findAllByProject = async (projectId: number): Promise<any[]> => {
  const query = `
    SELECT rut.*,
      GREATEST(0, rut.founder_quota - (
        SELECT COUNT(*) FROM residence_units ru 
        WHERE ru.unit_type_id = rut.id AND ru.status != 'AVAILABLE'
      )) as founder_available_count,
      (SELECT COUNT(*) FROM residence_units ru WHERE ru.unit_type_id = rut.id AND ru.status = 'AVAILABLE') as total_available_count
    FROM residence_unit_types rut
    WHERE rut.residence_project_id = ? 
    ORDER BY rut.id ASC
  `;
  const [rows] = await pool.query<any[]>(query, [projectId]);
  return rows;
};

export const findById = async (id: number): Promise<ResidenceUnitType | null> => {
  const [rows] = await pool.query<ResidenceUnitType[]>('SELECT * FROM residence_unit_types WHERE id = ?', [id]);
  return rows[0] || null;
};

export const findByCode = async (projectId: number, code: string): Promise<ResidenceUnitType | null> => {
  const [rows] = await pool.query<ResidenceUnitType[]>('SELECT * FROM residence_unit_types WHERE residence_project_id = ? AND code = ?', [projectId, code]);
  return rows[0] || null;
};

export const create = async (projectId: number, data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  
  const query = `
    INSERT INTO residence_unit_types 
    (residence_project_id, code, name, surface, founder_price, founder_quota, public_price, parking_available, description, plan_image_url)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;
  
  const [result] = await (db as any).query(query, [
    projectId,
    data.code,
    data.name,
    data.surface,
    data.founder_price,
    data.founder_quota || 0,
    data.public_price,
    data.parking_available || false,
    data.description || null,
    data.plan_image_url || null
  ]);
  
  return (result as ResultSetHeader).insertId;
};

export const update = async (id: number, data: any, connection?: any): Promise<void> => {
  const db = connection || pool;
  
  const query = `
    UPDATE residence_unit_types 
    SET code = COALESCE(?, code),
        name = COALESCE(?, name),
        surface = COALESCE(?, surface),
        founder_price = COALESCE(?, founder_price),
        founder_quota = COALESCE(?, founder_quota),
        public_price = COALESCE(?, public_price),
        parking_available = COALESCE(?, parking_available),
        description = COALESCE(?, description),
        plan_image_url = COALESCE(?, plan_image_url)
    WHERE id = ?
  `;
  
  await (db as any).query(query, [
    data.code !== undefined ? data.code : null,
    data.name !== undefined ? data.name : null,
    data.surface !== undefined ? data.surface : null,
    data.founder_price !== undefined ? data.founder_price : null,
    data.founder_quota !== undefined ? data.founder_quota : null,
    data.public_price !== undefined ? data.public_price : null,
    data.parking_available !== undefined ? data.parking_available : null,
    data.description !== undefined ? data.description : null,
    data.plan_image_url !== undefined ? data.plan_image_url : null,
    id
  ]);
};

export const remove = async (id: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await (db as any).query('DELETE FROM residence_unit_types WHERE id = ?', [id]);
};
