import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface Payment extends RowDataPacket {
  id: number;
  payment_schedule_item_id: number;
  amount: number;
  payment_date: Date;
  payment_method: string | null;
  reference: string | null;
  proof_document_id: number | null;
  notes: string | null;
  recorded_by: number | null;
  created_at: Date;
}

export const findAllWithAcquirers = async (): Promise<(Payment & { acquirer_first_name: string; acquirer_last_name: string; item_label: string; unit_id: number })[]> => {
  const query = `
    SELECT p.*, u.first_name as acquirer_first_name, u.last_name as acquirer_last_name, psi.label as item_label, ps.unit_id, ps.acquirer_id
    FROM payments p
    JOIN payment_schedule_items psi ON p.payment_schedule_item_id = psi.id
    JOIN payment_schedules ps ON psi.payment_schedule_id = ps.id
    JOIN acquirer_profiles a ON ps.acquirer_id = a.id
    JOIN users u ON a.user_id = u.id
    ORDER BY p.payment_date DESC, p.created_at DESC
  `;
  const [rows] = await pool.query(query);
  return rows as any;
};

export const findByItemId = async (itemId: number): Promise<Payment[]> => {
  const [rows] = await pool.query<Payment[]>('SELECT * FROM payments WHERE payment_schedule_item_id = ? ORDER BY payment_date DESC, created_at DESC', [itemId]);
  return rows;
};

export const findById = async (id: number, connection?: any): Promise<Payment | null> => {
  const db = connection || pool;
  const [rows] = await (db as any).query('SELECT * FROM payments WHERE id = ?', [id]);
  return rows[0] || null;
};

export const create = async (itemId: number, data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  const query = `
    INSERT INTO payments 
    (payment_schedule_item_id, amount, payment_date, payment_method, reference, proof_document_id, notes, recorded_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
  `;
  const [result] = await (db as any).query(query, [
    itemId,
    data.amount,
    data.payment_date,
    data.payment_method || null,
    data.reference || null,
    data.proof_document_id || null,
    data.notes || null,
    data.recorded_by || 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 payments 
    SET amount = COALESCE(?, amount),
        payment_date = COALESCE(?, payment_date),
        payment_method = COALESCE(?, payment_method),
        reference = COALESCE(?, reference),
        proof_document_id = COALESCE(?, proof_document_id),
        notes = COALESCE(?, notes)
    WHERE id = ?
  `;
  await (db as any).query(query, [
    data.amount !== undefined ? data.amount : null,
    data.payment_date !== undefined ? data.payment_date : null,
    data.payment_method !== undefined ? data.payment_method : null,
    data.reference !== undefined ? data.reference : null,
    data.proof_document_id !== undefined ? data.proof_document_id : null,
    data.notes !== undefined ? data.notes : null,
    id
  ]);
};

export const remove = async (id: number, connection?: any): Promise<void> => {
  const db = connection || pool;
  await (db as any).query('DELETE FROM payments WHERE id = ?', [id]);
};

export const getTotalPaidForItem = async (itemId: number, connection?: any): Promise<number> => {
  const db = connection || pool;
  const [rows] = await (db as any).query('SELECT SUM(amount) as total FROM payments WHERE payment_schedule_item_id = ?', [itemId]);
  return Number(rows[0].total) || 0;
};

export const findPaymentDetailsForReceipt = async (itemId: number): Promise<any> => {
  const query = `
    SELECT 
      u.email as acquirer_email,
      CONCAT(u.first_name, ' ', u.last_name) as acquirer_name,
      psi.label as item_label,
      psi.amount as item_amount,
      ru.reference as unit_number,
      rp.name as project_name,
      (ps.total_amount - (
        SELECT COALESCE(SUM(p2.amount), 0)
        FROM payments p2
        JOIN payment_schedule_items psi2 ON p2.payment_schedule_item_id = psi2.id
        WHERE psi2.payment_schedule_id = ps.id
      )) as total_remaining
    FROM payment_schedule_items psi
    JOIN payment_schedules ps ON psi.payment_schedule_id = ps.id
    JOIN acquirer_profiles a ON ps.acquirer_id = a.id
    JOIN users u ON a.user_id = u.id
    JOIN residence_units ru ON ps.unit_id = ru.id
    LEFT JOIN residence_projects rp ON ru.residence_project_id = rp.id
    WHERE psi.id = ?
  `;
  const [rows] = await pool.query(query, [itemId]);
  return (rows as any[])[0] || null;
};
