import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface SentEmail extends RowDataPacket {
  id: number;
  recipient: string;
  recipient_name: string | null;
  from_email: string;
  reply_to: string | null;
  subject: string;
  body_html: string;
  body_text: string | null;
  email_type: string;
  status: 'SENT' | 'FAILED' | 'SIMULATED';
  error_message: string | null;
  metadata: any;
  created_at: string;
  updated_at: string;
}

export interface CreateSentEmailInput {
  recipient: string;
  recipient_name?: string | null;
  from_email: string;
  reply_to?: string | null;
  subject: string;
  body_html: string;
  body_text?: string | null;
  email_type: string;
  status: 'SENT' | 'FAILED' | 'SIMULATED';
  error_message?: string | null;
  metadata?: any;
}

export interface FindSentEmailsPaginatedResult {
  data: SentEmail[];
  total: number;
}

export interface SentEmailStats {
  total: number;
  sent: number;
  failed: number;
  simulated: number;
  todayCount: number;
}

export const create = async (data: CreateSentEmailInput, connection?: any): Promise<number> => {
  const db = connection || pool;
  const query = `
    INSERT INTO sent_emails (
      recipient,
      recipient_name,
      from_email,
      reply_to,
      subject,
      body_html,
      body_text,
      email_type,
      status,
      error_message,
      metadata
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  const metaString = data.metadata ? JSON.stringify(data.metadata) : null;

  const [result] = await db.query(query, [
    data.recipient,
    data.recipient_name || null,
    data.from_email,
    data.reply_to || null,
    data.subject,
    data.body_html,
    data.body_text || null,
    data.email_type,
    data.status,
    data.error_message || null,
    metaString,
  ]);

  return (result as ResultSetHeader).insertId;
};

export const findById = async (id: number, connection?: any): Promise<SentEmail | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM sent_emails WHERE id = ?', [id]);
  const emails = rows as SentEmail[];
  if (!emails || emails.length === 0) return null;

  const email = emails[0];
  if (email.metadata && typeof email.metadata === 'string') {
    try {
      email.metadata = JSON.parse(email.metadata);
    } catch {
      // keep raw if not JSON
    }
  }
  return email;
};

export const findAllPaginated = async (
  page: number = 1,
  limit: number = 20,
  search?: string,
  type?: string,
  status?: string,
  connection?: any
): Promise<FindSentEmailsPaginatedResult> => {
  const db = connection || pool;

  let query = 'SELECT * FROM sent_emails';
  let countQuery = 'SELECT COUNT(*) as total FROM sent_emails';
  const queryParams: any[] = [];
  const whereClauses: string[] = [];

  if (status && status !== 'ALL') {
    whereClauses.push('status = ?');
    queryParams.push(status);
  }

  if (type && type !== 'ALL') {
    whereClauses.push('email_type = ?');
    queryParams.push(type);
  }

  if (search && search.trim().length > 0) {
    whereClauses.push('(recipient LIKE ? OR recipient_name LIKE ? OR subject LIKE ? OR email_type LIKE ?)');
    const searchTerm = `%${search.trim()}%`;
    queryParams.push(searchTerm, searchTerm, searchTerm, searchTerm);
  }

  if (whereClauses.length > 0) {
    const whereStr = ' WHERE ' + whereClauses.join(' AND ');
    query += whereStr;
    countQuery += whereStr;
  }

  const [countRows] = await db.query(countQuery, queryParams);
  const total = (countRows as any[])[0]?.total || 0;

  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = Math.max(0, (page - 1) * limit);
  const allParams = [...queryParams, Number(limit), Number(offset)];

  const [rows] = await db.query(query, allParams);
  const items = (rows as SentEmail[]).map((email) => {
    if (email.metadata && typeof email.metadata === 'string') {
      try {
        email.metadata = JSON.parse(email.metadata);
      } catch {
        // ignore
      }
    }
    return email;
  });

  return {
    data: items,
    total,
  };
};

export const getStats = async (connection?: any): Promise<SentEmailStats> => {
  const db = connection || pool;
  const query = `
    SELECT 
      COUNT(*) as total,
      SUM(CASE WHEN status = 'SENT' THEN 1 ELSE 0 END) as sent,
      SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) as failed,
      SUM(CASE WHEN status = 'SIMULATED' THEN 1 ELSE 0 END) as simulated,
      SUM(CASE WHEN DATE(created_at) = CURRENT_DATE THEN 1 ELSE 0 END) as todayCount
    FROM sent_emails
  `;

  const [rows] = await db.query(query);
  const row = (rows as any[])[0] || {};

  return {
    total: Number(row.total || 0),
    sent: Number(row.sent || 0),
    failed: Number(row.failed || 0),
    simulated: Number(row.simulated || 0),
    todayCount: Number(row.todayCount || 0),
  };
};

export const deleteById = async (id: number, connection?: any): Promise<boolean> => {
  const db = connection || pool;
  const [result] = await db.query('DELETE FROM sent_emails WHERE id = ?', [id]);
  return (result as ResultSetHeader).affectedRows > 0;
};
