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

export interface ResidenceMedia extends RowDataPacket {
  id: number;
  residence_project_id: number;
  type: 'IMAGE' | 'VIDEO' | 'VIRTUAL_TOUR';
  file_url: string;
  caption: string | null;
  sort_order: number;
  is_primary: boolean;
  created_at: Date;
}

export const findAllByProject = async (projectId: number): Promise<ResidenceMedia[]> => {
  const [rows] = await pool.query<ResidenceMedia[]>('SELECT * FROM residence_project_media WHERE residence_project_id = ? ORDER BY sort_order ASC, created_at DESC', [projectId]);
  return rows;
};

export const findById = async (id: number): Promise<ResidenceMedia | null> => {
  const [rows] = await pool.query<ResidenceMedia[]>('SELECT * FROM residence_project_media WHERE id = ?', [id]);
  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_project_media 
    (residence_project_id, type, file_url, caption, sort_order, is_primary)
    VALUES (?, ?, ?, ?, ?, ?)
  `;
  
  const [result] = await (db as any).query(query, [
    projectId,
    data.type,
    data.file_url,
    data.caption || null,
    data.sort_order || 0,
    data.is_primary || false
  ]);
  
  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_project_media 
    SET type = COALESCE(?, type),
        file_url = COALESCE(?, file_url),
        caption = COALESCE(?, caption),
        sort_order = COALESCE(?, sort_order),
        is_primary = COALESCE(?, is_primary)
    WHERE id = ?
  `;
  
  await (db as any).query(query, [
    data.type !== undefined ? data.type : null,
    data.file_url !== undefined ? data.file_url : null,
    data.caption !== undefined ? data.caption : null,
    data.sort_order !== undefined ? data.sort_order : null,
    data.is_primary !== undefined ? data.is_primary : null,
    id
  ]);
};

export const resetPrimaryForProject = async (projectId: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await (db as any).query('UPDATE residence_project_media SET is_primary = FALSE WHERE residence_project_id = ?', [projectId]);
};

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