import 'dotenv/config';
import { test, expect } from '@playwright/test';
import { ImapFlow } from 'imapflow';
import { simpleParser } from 'mailparser';

import { login, apiHeaders } from '../smoke/helpers';

/**
 * Real-API spec for the system-path send (Phase A PR8).
 *
 * Composes via the email composer with senderType=system, asserts the message
 * lands in the configured IMAP mailbox via the port-config noreply identity,
 * and verifies the attachment bytes round-trip end-to-end.
 *
 * Requires:
 *   SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASS - outbound transport
 *   IMAP_HOST / IMAP_PORT / IMAP_USER / IMAP_PASS - inbound for verification
 */

const SMTP_HOST = process.env.SMTP_HOST;
const IMAP_HOST = process.env.IMAP_HOST;
const IMAP_PORT = process.env.IMAP_PORT ? Number(process.env.IMAP_PORT) : 993;
const IMAP_USER = process.env.IMAP_USER;
const IMAP_PASS = process.env.IMAP_PASS;

test.describe('SMTP system-path send', () => {
  test.skip(!SMTP_HOST || !IMAP_HOST || !IMAP_USER || !IMAP_PASS, 'SMTP/IMAP env not configured');

  test.beforeEach(async ({ page }) => {
    await login(page, 'super_admin');
  });

  test('system send → IMAP fetch → attachment bytes match', async ({ page }) => {
    const headers = await apiHeaders(page);

    // 1. Upload a small file we'll attach to the email.
    const sentinel = `phase-a-attach-${Date.now()}`;
    const uploadRes = await page.request.post('/api/v1/files', {
      headers,
      multipart: {
        file: {
          name: 'phase-a.txt',
          mimeType: 'text/plain',
          buffer: Buffer.from(sentinel),
        },
      },
    });
    expect(uploadRes.ok(), `upload: ${uploadRes.status()}`).toBe(true);
    const uploadBody = (await uploadRes.json()) as { data: { id: string } };

    // 2. Compose via system path
    const subject = `Phase A system send ${Date.now()}`;
    const sendRes = await page.request.post('/api/v1/email/compose', {
      headers,
      data: {
        senderType: 'system',
        to: [IMAP_USER!],
        subject,
        bodyHtml: '<p>System-path send.</p>',
        attachments: [{ fileId: uploadBody.data.id, filename: 'phase-a.txt' }],
      },
    });
    expect(sendRes.ok(), `compose: ${sendRes.status()} ${await sendRes.text()}`).toBe(true);

    // 3. Poll IMAP for the message.
    const client = new ImapFlow({
      host: IMAP_HOST!,
      port: IMAP_PORT,
      secure: IMAP_PORT === 993,
      auth: { user: IMAP_USER!, pass: IMAP_PASS! },
      logger: false,
    });
    await client.connect();
    try {
      let attempts = 0;
      let attachmentMatched = false;
      while (attempts++ < 18 && !attachmentMatched) {
        await new Promise((r) => setTimeout(r, 5_000));
        const lock = await client.getMailboxLock('INBOX');
        try {
          for await (const msg of client.fetch({ subject } as never, { source: true })) {
            const parsed = await simpleParser(msg.source as Buffer);
            const att = parsed.attachments.find((a) => a.filename === 'phase-a.txt');
            if (att && att.content.toString() === sentinel) {
              attachmentMatched = true;
              break;
            }
          }
        } finally {
          lock.release();
        }
      }
      expect(attachmentMatched, 'attachment bytes match').toBe(true);
    } finally {
      await client.logout();
    }
  });
});
