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

export interface Document extends RowDataPacket {
  id: number;
  owner_user_id: number;
  acquirer_id: number | null;
  residence_project_id: number | null;
  category: 'RESERVATION_CONTRACT' | 'CERTIFICATE' | 'INVOICE' | 'PAYMENT_PROOF' | 'OTHER';
  title: string;
  file_name: string;
  file_path: string;
  mime_type: string;
  file_size: number;
  uploaded_by: number | null;
  is_private: boolean;
  created_at: Date;
}

export const findAllWithOwners = async (): Promise<(Document & { owner_first_name: string; owner_last_name: string })[]> => {
  const query = `
    SELECT d.*, u.first_name as owner_first_name, u.last_name as owner_last_name 
    FROM documents d
    LEFT JOIN users u ON d.owner_user_id = u.id
    ORDER BY d.created_at DESC
  `;
  const [rows] = await pool.query(query);
  return rows as any;
};

export const findByOwnerId = async (ownerId: number): Promise<Document[]> => {
  const [rows] = await pool.query<Document[]>('SELECT * FROM documents WHERE owner_user_id = ? ORDER BY created_at DESC', [ownerId]);
  return rows;
};

export const findByAcquirerId = async (acquirerId: number): Promise<Document[]> => {
  const [rows] = await pool.query<Document[]>('SELECT * FROM documents WHERE acquirer_id = ? ORDER BY created_at DESC', [acquirerId]);
  return rows;
};

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

export const create = async (data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  const query = `
    INSERT INTO documents 
    (owner_user_id, acquirer_id, residence_project_id, category, title, file_name, file_path, mime_type, file_size, uploaded_by, is_private)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;
  const [result] = await (db as any).query(query, [
    data.owner_user_id,
    data.acquirer_id || null,
    data.residence_project_id || null,
    data.category,
    data.title,
    data.file_name,
    data.file_path,
    data.mime_type,
    data.file_size,
    data.uploaded_by || null,
    data.is_private !== undefined ? data.is_private : true
  ]);
  return (result as ResultSetHeader).insertId;
};

export const update = async (id: number, data: any, connection?: any): Promise<void> => {
  const db = connection || pool;
  const query = `
    UPDATE documents 
    SET title = COALESCE(?, title),
        category = COALESCE(?, category),
        is_private = COALESCE(?, is_private)
    WHERE id = ?
  `;
  await (db as any).query(query, [
    data.title !== undefined ? data.title : null,
    data.category !== undefined ? data.category : null,
    data.is_private !== undefined ? data.is_private : null,
    id
  ]);
};

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