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

export interface ContactMessage extends RowDataPacket {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  phone: string | null;
  subject: string | null;
  message: string;
  status: 'NEW' | 'READ' | 'REPLIED' | 'ARCHIVED';
  handled_by: number | null;
  created_at: string;
  updated_at: string;
}

export const findAll = async (connection?: any): Promise<ContactMessage[]> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM contact_messages ORDER BY created_at DESC');
  return rows as ContactMessage[];
};

export interface FindAllPaginatedResult {
  data: ContactMessage[];
  total: number;
}

export const findAllPaginated = async (
  page: number, 
  limit: number, 
  search?: string, 
  status?: string, 
  connection?: any
): Promise<FindAllPaginatedResult> => {
  const db = connection || pool;
  
  let query = 'SELECT * FROM contact_messages';
  let countQuery = 'SELECT COUNT(*) as total FROM contact_messages';
  const queryParams: any[] = [];
  const whereClauses: string[] = [];
  
  if (status && status !== 'ALL') {
    whereClauses.push('status = ?');
    queryParams.push(status);
  }
  
  if (search) {
    whereClauses.push('(first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR subject LIKE ?)');
    const searchTerm = `%${search}%`;
    queryParams.push(searchTerm, searchTerm, searchTerm, searchTerm);
  }
  
  if (whereClauses.length > 0) {
    const whereStr = ' WHERE ' + whereClauses.join(' AND ');
    query += whereStr;
    countQuery += whereStr;
  }
  
  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * limit;
  const allParams = [...queryParams, limit, offset];
  
  const [countRows] = await db.query(countQuery, queryParams);
  const total = (countRows as any[])[0].total;
  
  const [rows] = await db.query(query, allParams);
  
  return {
    data: rows as ContactMessage[],
    total
  };
};

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

export const create = async (data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  const query = `
    INSERT INTO contact_messages (first_name, last_name, email, phone, subject, message)
    VALUES (?, ?, ?, ?, ?, ?)
  `;
  const [result] = await db.query(query, [
    data.first_name, data.last_name, data.email, data.phone || null, data.subject || null, data.message
  ]);
  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} = ?`);
      params.push(value);
    }
  }
  
  if (updates.length > 0) {
    params.push(id);
    await db.query(`UPDATE contact_messages SET ${updates.join(', ')} WHERE id = ?`, params);
  }
};
