type ValidateImapParams = {
  host: string;
  port: number;
  secure: boolean;
  user: string;
  pass?: string;
  accessToken?: string;
};

type ValidateImapResult = { ok: true; folderCount: number } | { ok: false; error: string };

export async function validateImapConnection(params: ValidateImapParams): Promise<ValidateImapResult> {
  const { ImapFlow } = await import('imapflow');

  const auth: { user: string; pass?: string; accessToken?: string } = { user: params.user };
  if (params.accessToken) {
    auth.accessToken = params.accessToken;
  } else if (params.pass) {
    auth.pass = params.pass;
  } else {
    return { ok: false, error: 'No authentication credentials provided' };
  }

  const client = new ImapFlow({
    host: params.host,
    port: params.port,
    secure: params.secure,
    auth,
    logger: false,
    greetingTimeout: 60_000,
    socketTimeout: 60_000,
  });

  try {
    const result = await Promise.race([
      (async () => {
        await client.connect();
        const folders = await client.list();
        await client.logout();
        return { ok: true as const, folderCount: folders.length };
      })(),
      new Promise<ValidateImapResult>((_, reject) =>
        setTimeout(() => reject(new Error('Connection timed out')), 90_000),
      ),
    ]);
    return result;
  } catch (err) {
    try {
      client.close();
    } catch {}
    const message = err instanceof Error ? err.message : 'Connection failed';
    return { ok: false, error: message };
  }
}
