import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface PropertyMedia extends RowDataPacket {
  id: number;
  property_id: number;
  type: 'IMAGE' | 'VIDEO' | 'VIRTUAL_TOUR';
  url: string;
  alt_text: string | null;
  sort_order: number;
  is_primary: boolean;
  created_at: string;
}

export const findAllByProperty = async (propertyId: number, connection?: any): Promise<PropertyMedia[]> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM property_media WHERE property_id = ? ORDER BY sort_order ASC, id ASC', [propertyId]);
  return rows;
};

export const findById = async (id: number, connection?: any): Promise<PropertyMedia | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM property_media WHERE id = ?', [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 property_media (property_id, type, url, alt_text, sort_order, is_primary)
    VALUES (?, ?, ?, ?, ?, ?)
  `;
  const [result] = await db.query(query, [
    propertyId, data.type, data.url, data.alt_text || null, data.sort_order || 0, data.is_primary ? 1 : 0
  ]);
  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} = ?`);
      if (typeof value === 'boolean') {
        params.push(value ? 1 : 0);
      } else {
        params.push(value);
      }
    }
  }
  
  if (updates.length > 0) {
    params.push(id);
    await db.query(`UPDATE property_media SET ${updates.join(', ')} WHERE id = ?`, params);
  }
};

export const resetPrimaryForProperty = async (propertyId: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await db.query('UPDATE property_media SET is_primary = 0 WHERE property_id = ? AND type = "IMAGE"', [propertyId]);
};

export const deleteById = async (id: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await db.query('DELETE FROM property_media WHERE id = ?', [id]);
};
