import 'server-only';

import type { SendEmailResult } from './email-provider';
import { SmtpEmailProvider } from './smtp-provider';
import {
  getEmailConfigurationByIdForUse,
  markEmailConfigurationTestResult,
} from './email-config.service';

export async function testEmailConfigurationConnection(input: {
  organizationId: string;
  userId: string;
  configurationId: string;
}) {
  const config = await getEmailConfigurationByIdForUse(input.organizationId, input.configurationId);
  if (!config) {
    throw new Error('Email configuration was not found.');
  }

  const provider = new SmtpEmailProvider();
  const result = await provider.testConnection(config);

  await markEmailConfigurationTestResult({
    organizationId: input.organizationId,
    userId: input.userId,
    id: config.id,
    status: result.ok ? 'passed' : 'failed',
    errorMessage: result.detail ?? null,
  });

  return result;
}

export async function sendTestEmail(input: {
  organizationId: string;
  userId: string;
  configurationId: string;
  recipientEmail: string;
}): Promise<SendEmailResult> {
  const config = await getEmailConfigurationByIdForUse(input.organizationId, input.configurationId);
  if (!config) {
    throw new Error('Email configuration was not found.');
  }

  const provider = new SmtpEmailProvider();

  try {
    const result = await provider.sendEmail(config, {
      subject: `ALLA OS test email from ${config.name}`,
      text: [
        'This is a test email from ALLA OS.',
        '',
        `Configuration: ${config.name}`,
        `SMTP host: ${config.host}:${config.port}`,
        `Sent at: ${new Date().toISOString()}`,
      ].join('\n'),
      html: [
        '<p>This is a test email from <strong>ALLA OS</strong>.</p>',
        `<p>Configuration: <strong>${config.name}</strong></p>`,
        `<p>SMTP host: <code>${config.host}:${config.port}</code></p>`,
        `<p>Sent at: <code>${new Date().toISOString()}</code></p>`,
      ].join(''),
      to: [{ email: input.recipientEmail.trim().toLowerCase() }],
    });

    await markEmailConfigurationTestResult({
      organizationId: input.organizationId,
      userId: input.userId,
      id: config.id,
      status: 'passed',
    });

    return result;
  } catch (error) {
    await markEmailConfigurationTestResult({
      organizationId: input.organizationId,
      userId: input.userId,
      id: config.id,
      status: 'failed',
      errorMessage: error instanceof Error ? error.message : 'Unknown email send failure',
    });

    throw error;
  }
}
