import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface EmailTemplateVariable {
  key: string;
  desc: string;
}

export interface EmailTemplate extends RowDataPacket {
  id: number;
  template_key: string;
  name: string;
  category: 'CLIENT' | 'ADMIN' | 'SECURITE' | 'FINANCE';
  subject: string;
  headline: string | null;
  body_content: string;
  action_button_text: string | null;
  action_button_url: string | null;
  footer_note: string | null;
  available_variables: EmailTemplateVariable[] | null;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export interface UpdateEmailTemplateInput {
  name?: string;
  subject?: string;
  headline?: string | null;
  body_content?: string;
  action_button_text?: string | null;
  action_button_url?: string | null;
  footer_note?: string | null;
  is_active?: boolean;
}

const parseVariables = (template: EmailTemplate): EmailTemplate => {
  if (template.available_variables && typeof template.available_variables === 'string') {
    try {
      template.available_variables = JSON.parse(template.available_variables as unknown as string);
    } catch {
      template.available_variables = [];
    }
  }
  return template;
};

export const findAll = async (connection?: any): Promise<EmailTemplate[]> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM email_templates ORDER BY category ASC, id ASC');
  return (rows as EmailTemplate[]).map(parseVariables);
};

export const findByKey = async (templateKey: string, connection?: any): Promise<EmailTemplate | null> => {
  const db = connection || pool;
  const [rows] = await db.query('SELECT * FROM email_templates WHERE template_key = ?', [templateKey]);
  const list = rows as EmailTemplate[];
  if (!list || list.length === 0) return null;
  return parseVariables(list[0]);
};

export const update = async (
  templateKey: string,
  data: UpdateEmailTemplateInput,
  connection?: any
): Promise<EmailTemplate | null> => {
  const db = connection || pool;
  const fields: string[] = [];
  const values: any[] = [];

  if (data.name !== undefined) {
    fields.push('name = ?');
    values.push(data.name);
  }
  if (data.subject !== undefined) {
    fields.push('subject = ?');
    values.push(data.subject);
  }
  if (data.headline !== undefined) {
    fields.push('headline = ?');
    values.push(data.headline);
  }
  if (data.body_content !== undefined) {
    fields.push('body_content = ?');
    values.push(data.body_content);
  }
  if (data.action_button_text !== undefined) {
    fields.push('action_button_text = ?');
    values.push(data.action_button_text);
  }
  if (data.action_button_url !== undefined) {
    fields.push('action_button_url = ?');
    values.push(data.action_button_url);
  }
  if (data.footer_note !== undefined) {
    fields.push('footer_note = ?');
    values.push(data.footer_note);
  }
  if (data.is_active !== undefined) {
    fields.push('is_active = ?');
    values.push(data.is_active ? 1 : 0);
  }

  if (fields.length === 0) {
    return findByKey(templateKey, db);
  }

  values.push(templateKey);
  const query = `UPDATE email_templates SET ${fields.join(', ')} WHERE template_key = ?`;
  await db.query(query, values);

  return findByKey(templateKey, db);
};
