import { api } from '../api';

export interface NewsletterSubscriber {
  id: number;
  email: string;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

export interface NewsletterSendData {
  subject: string;
  content: string; // backend accepts either 'content' or 'body'
}

export const getNewsletterSubscribers = async (): Promise<NewsletterSubscriber[]> => {
  const response = await api.get<NewsletterSubscriber[]>(`/admin/newsletter/subscribers`);
  return response.data;
};

export const sendNewsletter = async (data: NewsletterSendData): Promise<{ message: string }> => {
  // Backend will accept either 'content' or 'body'. We send 'content'.
  const response = await api.post<{ message: string }>(
    `/admin/newsletter/send`,
    {
      subject: data.subject,
      content: data.content,
    },
    // Increase timeout to 60s to accommodate SMTP and bulk send delays
    { timeout: 60000 }
  );
  return response.data;
};

export const sendNewsletterTest = async (email?: string): Promise<{ message: string; recipient: string }> => {
  const payload = email ? { email } : {};
  // Allow more time for SMTP connection during test sends
  const response = await api.post<{ message: string; recipient: string }>(
    `/admin/newsletter/test`,
    payload,
    { timeout: 60000 }
  );
  return response.data;
};

export type NewsletterTestType = 'newsletter' | 'welcome' | 'welcome_back' | 'blogs' | 'events' | 'matches' | 'scores' | 'weekly';
export interface NewsletterTestPayload {
  email?: string;
  emails?: string[];
  type?: NewsletterTestType;
}

export type AdminSmtpTestPayload = {
  host: string;
  port: number;
  username?: string;
  password?: string;
  from: string;
  to: string;
  subject?: string;
  body?: string;
  use_tls?: boolean;
};

export const adminSendSmtpTest = async (payload: AdminSmtpTestPayload): Promise<{ ok: boolean; message?: string; error?: string }> => {
  const res = await api.post('/admin/newsletter/smtp-test', payload, { timeout: 60000 });
  return res.data;
};

export const sendNewsletterTestAdvanced = async (payload: NewsletterTestPayload): Promise<{ message: string; recipients?: string[]; recipient?: string; type: string }> => {
  // Allow more time for SMTP connection during test sends
  const response = await api.post<{ message: string; recipients?: string[]; recipient?: string; type: string }>(
    `/admin/newsletter/test`,
    payload,
    { timeout: 60000 }
  );
  return response.data;
};

export interface NewsletterStatus {
  total_subscribers: number;
  active_subscribers: number;
  sample_recipients: string[];
  interval_minutes: number;
  next_approximate: string;
  newsletter_enabled?: boolean;
}

export const getNewsletterStatus = async (): Promise<NewsletterStatus> => {
  const response = await api.get<NewsletterStatus>(`/admin/newsletter/status`);
  return response.data as any;
};

export type DigestType = 'blogs' | 'events' | 'matches' | 'scores' | 'weekly';

export const sendNewsletterDigest = async (type: DigestType, competitions?: string): Promise<{ message: string; recipients: number; type: string }> => {
  const response = await api.post(`/admin/newsletter/send-digest`, { type, competitions });
  return response.data;
};

export const setNewsletterAutomation = async (enabled: boolean): Promise<{ newsletter_enabled: boolean }> => {
  const response = await api.patch(`/admin/newsletter/enable`, { enabled });
  return response.data;
};

export interface NewsletterPreviewPayload {
  preferences?: Record<string, boolean> & { competitions?: string };
}
export interface NewsletterPreviewResponse {
  subject: string;
  html: string;
}

export const previewNewsletter = async (payload: NewsletterPreviewPayload): Promise<NewsletterPreviewResponse> => {
  const response = await api.post<NewsletterPreviewResponse>(`/admin/newsletter/preview`, payload);
  return response.data;
};

export interface EmailStatRow {
  id: number;
  created_at: string;
  subject: string;
  recipient: string;
  type: string;
  status: string;
  opens: number;
  clicks: number;
  spam: number;
  unsubs: number;
}

export const getRecentEmailStats = async (): Promise<EmailStatRow[]> => {
  const response = await api.get<{ data: EmailStatRow[] }>(`/admin/newsletter/stats/recent`);
  return response.data?.data || [];
};

export interface EmailEventRow {
  id: number;
  created_at: string;
  email_log_id: number;
  event_type: string;
  meta?: Record<string, any>;
}

export const getEmailEventsForLog = async (id: number): Promise<EmailEventRow[]> => {
  const response = await api.get<{ data: EmailEventRow[] }>(`/admin/newsletter/stats/${id}/events`);
  return response.data?.data || [];
};

export const deleteSubscriber = async (id: number): Promise<void> => {
  await api.delete(`/admin/newsletter/subscribers/${id}`);
};

export const toggleSubscriberStatus = async (id: number, isActive: boolean): Promise<NewsletterSubscriber> => {
  const response = await api.patch<NewsletterSubscriber>(
    `/admin/newsletter/subscribers/${id}/status`,
    { is_active: isActive }
  );
  return response.data;
};

export const updateSubscriberPreferences = async (id: number, preferences: Record<string, boolean>) => {
  const response = await api.patch<NewsletterSubscriber>(`/admin/newsletter/subscribers/${id}/preferences`, preferences);
  return response.data;
};
