import type { Page } from '@playwright/test';
import { siteConfig } from '../config/siteConfig';

const EMAIL_DOMAIN = 'e2e.staging.matsuyaginza.com';

export interface ReceivedEmail {
    messageId: string;
    from: string;
    to: string[];
    subject: string;
    textBody: string;
    htmlBody: string;
    date: string | null;
    s3Key: string;
}

/**
 * Generate a unique test email address.
 * Each test run gets a unique address to avoid conflicts.
 */
export function generateTestEmail(prefix = 'e2e'): string {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2, 6);
    return `${prefix}-${timestamp}-${random}@${EMAIL_DOMAIN}`;
}

/**
 * Wait for an email to arrive via the app's API.
 * The API polls S3 internally and returns when an email is found.
 */
export async function waitForEmail(
    page: Page,
    toAddress: string,
    options: {
        timeoutMs?: number;
        subjectContains?: string;
        afterDate?: Date;
    } = {}
): Promise<ReceivedEmail | null> {
    const { timeoutMs = 60000, subjectContains, afterDate } = options;
    const baseUrl = siteConfig.baseUrl || 'http://localhost:3000';

    const params = new URLSearchParams({ to: toAddress, timeout: timeoutMs.toString() });
    if (subjectContains) params.set('subject', subjectContains);
    if (afterDate) params.set('after', afterDate.toISOString());

    try {
        const response = await page.request.get(`${baseUrl}/api/emails?${params}`);
        if (response.ok()) {
            return await response.json();
        }
        return null;
    } catch {
        return null;
    }
}

/**
 * Clear all emails for an address (call before test to start clean).
 */
export async function clearEmails(page: Page, toAddress: string): Promise<void> {
    const baseUrl = siteConfig.baseUrl || 'http://localhost:3000';
    await page.request.delete(`${baseUrl}/api/emails?to=${encodeURIComponent(toAddress)}`).catch(() => {});
}

/**
 * Extract all links from email HTML body.
 */
export function extractLinksFromHtml(html: string): string[] {
    const linkRegex = /href=["']([^"']+)["']/gi;
    const links: string[] = [];
    let match;
    while ((match = linkRegex.exec(html)) !== null) {
        links.push(match[1]);
    }
    return links;
}

/**
 * Check if email contains expected content (supports both text and HTML).
 */
export function emailContains(email: ReceivedEmail, text: string): boolean {
    const lower = text.toLowerCase();
    return (
        email.textBody.toLowerCase().includes(lower) ||
        email.htmlBody.toLowerCase().includes(lower) ||
        email.subject.toLowerCase().includes(lower)
    );
}
