import assert from 'node:assert/strict';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { test } from 'node:test';

import {
  createDomain,
  createInboundMailbox,
  createUser,
  createWebmailLoginTicket,
  cleanupWebmailSessions,
  exchangeWebmailLoginTicket,
  initDatabase,
  replaceInboundMailboxGrants,
  revokeWebmailCredential,
  updateUserStatus,
  verifyInboundMailboxCredentialAsync,
  verifySmtpCredential,
  verifyWebmailCredential,
  verifyWebmailCredentialAsync,
  webmailSessionHasPermission
} from '../src/db.js';

const webmailAudience = 'https://mail.us.ss5.xyz';

test('Webmail login tickets are single-use and raw secrets never enter SQLite', async () => {
  const { database, owner, mailbox } = setupMailbox('single-use');
  const created = createWebmailLoginTicket(owner.id, mailbox.id, {
    audience: `${webmailAudience}/`
  });

  assert.match(created.ticket, /^mht_[A-Za-z0-9_-]{43}$/);
  assert.equal(created.audience, webmailAudience);
  const beforeExchange = database
    .prepare('SELECT * FROM webmail_sessions WHERE id = ?')
    .get(created.id);
  assert.equal(beforeExchange.credential_hash, null);
  assert.match(beforeExchange.ticket_hash, /^[a-f0-9]{64}$/);
  assert.equal(JSON.stringify(beforeExchange).includes(created.ticket), false);

  const exchanged = exchangeWebmailLoginTicket(created.ticket, { audience: webmailAudience });
  assert.match(exchanged.credential, /^mhw_[A-Za-z0-9_-]{43}$/);
  assert.equal(exchanged.address, mailbox.address);
  assert.equal(exchangeWebmailLoginTicket(created.ticket, { audience: webmailAudience }), null);

  const stored = database
    .prepare('SELECT * FROM webmail_sessions WHERE id = ?')
    .get(created.id);
  assert.match(stored.credential_hash, /^[a-f0-9]{64}$/);
  assert.equal(JSON.stringify(stored).includes(created.ticket), false);
  assert.equal(JSON.stringify(stored).includes(exchanged.credential), false);

  const syncAuth = verifyWebmailCredential(mailbox.address, exchanged.credential, { permission: 'receive' });
  assert.equal(syncAuth.user.id, owner.id);
  assert.equal(syncAuth.mailbox.id, mailbox.id);
  assert.ok(syncAuth.webmailSession.lastUsedAt);
  const asyncAuth = await verifyWebmailCredentialAsync(mailbox.address, exchanged.credential, {
    permission: 'send'
  });
  assert.equal(asyncAuth.user.id, owner.id);
  assert.equal(
    (await verifyInboundMailboxCredentialAsync(mailbox.address, exchanged.credential)).user.id,
    owner.id
  );
  assert.equal(verifySmtpCredential(mailbox.address, exchanged.credential).user.id, owner.id);
});

test('Webmail sessions require owner or explicit current mailbox grants without admin bypass', () => {
  const { owner, mailbox } = setupMailbox('grants');
  const admin = createUser({
    username: 'sso-admin',
    email: 'sso-admin@example.com',
    password: 'password123',
    role: 'admin'
  });
  const delegate = createUser({
    username: 'sso-delegate',
    email: 'sso-delegate@example.com',
    password: 'password123'
  });

  assert.throws(
    () => createWebmailLoginTicket(admin.id, mailbox.id, { audience: webmailAudience }),
    /无权登录/
  );
  assert.throws(
    () => createWebmailLoginTicket(delegate.id, mailbox.id, { audience: webmailAudience }),
    /无权登录/
  );

  replaceInboundMailboxGrants(mailbox.id, [{
    userId: delegate.id,
    permissions: { receive: true, send: false }
  }]);
  const ticket = createWebmailLoginTicket(delegate.id, mailbox.id, { audience: webmailAudience });
  const session = exchangeWebmailLoginTicket(ticket.ticket, { audience: webmailAudience });
  assert.equal(
    verifyWebmailCredential(mailbox.address, session.credential, { permission: 'receive' }).user.id,
    delegate.id
  );
  assert.equal(verifyWebmailCredential(mailbox.address, session.credential, { permission: 'send' }), null);
  assert.equal(verifySmtpCredential(mailbox.address, session.credential), null);

  replaceInboundMailboxGrants(mailbox.id, [{
    userId: delegate.id,
    permissions: { receive: true, send: true }
  }]);
  assert.equal(
    verifyWebmailCredential(mailbox.address, session.credential, { permission: 'send' }).user.id,
    delegate.id
  );
  const smtpAuth = verifySmtpCredential(mailbox.address, session.credential);
  assert.equal(smtpAuth.user.id, delegate.id);
  assert.equal(smtpAuth.webmailSession.id, session.id);
  assert.equal(webmailSessionHasPermission(session.id, mailbox.address, { permission: 'send' }), true);

  replaceInboundMailboxGrants(mailbox.id, []);
  assert.equal(webmailSessionHasPermission(session.id, mailbox.address, { permission: 'send' }), false);
  assert.equal(verifyWebmailCredential(mailbox.address, session.credential, { permission: 'receive' }), null);
  assert.equal(verifyWebmailCredential(mailbox.address, session.credential, { permission: 'send' }), null);

  const ownerTicket = createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
  const ownerSession = exchangeWebmailLoginTicket(ownerTicket.ticket, { audience: webmailAudience });
  assert.equal(
    verifyWebmailCredential(mailbox.address, ownerSession.credential, { permission: 'send' }).user.id,
    owner.id
  );
});

test('Webmail tickets and credentials honor expiry, revocation, audience and active users', () => {
  const { database, owner, mailbox } = setupMailbox('lifecycle');
  const expiredTicket = createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
  database
    .prepare('UPDATE webmail_sessions SET ticket_expires_at = ? WHERE id = ?')
    .run('2000-01-01T00:00:00.000Z', expiredTicket.id);
  assert.equal(exchangeWebmailLoginTicket(expiredTicket.ticket, { audience: webmailAudience }), null);

  const audienceTicket = createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
  assert.equal(
    exchangeWebmailLoginTicket(audienceTicket.ticket, { audience: 'https://other.example' }),
    null
  );
  const audienceSession = exchangeWebmailLoginTicket(audienceTicket.ticket, { audience: webmailAudience });
  assert.equal(
    revokeWebmailCredential(audienceSession.credential, { audience: 'https://other.example' }),
    false
  );
  assert.ok(verifyWebmailCredential(mailbox.address, audienceSession.credential));
  assert.equal(revokeWebmailCredential(audienceSession.credential, { audience: webmailAudience }), true);
  assert.equal(revokeWebmailCredential(audienceSession.credential, { audience: webmailAudience }), false);
  assert.equal(verifyWebmailCredential(mailbox.address, audienceSession.credential), null);

  const expiredCredentialTicket = createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
  const expiredCredential = exchangeWebmailLoginTicket(expiredCredentialTicket.ticket, {
    audience: webmailAudience
  });
  database
    .prepare('UPDATE webmail_sessions SET credential_expires_at = ? WHERE id = ?')
    .run('2000-01-01T00:00:00.000Z', expiredCredential.id);
  assert.equal(verifyWebmailCredential(mailbox.address, expiredCredential.credential), null);

  const disabledUserTicket = createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
  const disabledUserSession = exchangeWebmailLoginTicket(disabledUserTicket.ticket, {
    audience: webmailAudience
  });
  updateUserStatus(owner.id, 'disabled');
  assert.equal(verifyWebmailCredential(mailbox.address, disabledUserSession.credential), null);
});

test('Webmail SSO validates absolute audiences and bounded TTL values', () => {
  const { owner, mailbox } = setupMailbox('validation');
  const create = (overrides = {}) => createWebmailLoginTicket(owner.id, mailbox.id, {
    audience: webmailAudience,
    ...overrides
  });

  assert.throws(() => create({ audience: 'mail.us.ss5.xyz' }), /受众地址/);
  assert.throws(() => create({ audience: `${webmailAudience}/login` }), /受众地址/);
  assert.throws(() => create({ ticketTtlSeconds: 9 }), /票据有效期/);
  assert.throws(() => create({ ticketTtlSeconds: 301 }), /票据有效期/);
  assert.throws(() => create({ credentialTtlSeconds: 299 }), /临时凭据有效期/);
  assert.throws(() => create({ credentialTtlSeconds: 86_401 }), /临时凭据有效期/);
  assert.doesNotThrow(() => create({ ticketTtlSeconds: 10, credentialTtlSeconds: 300 }));
  assert.doesNotThrow(() => create({ ticketTtlSeconds: 300, credentialTtlSeconds: 86_400 }));
});

test('Webmail ticket issuance is rate limited and bounds active sessions per mailbox', () => {
  const { database, owner, mailbox } = setupMailbox('bounded');
  const credentials = [];
  for (let index = 0; index < 6; index += 1) {
    const ticket = createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
    const session = exchangeWebmailLoginTicket(ticket.ticket, { audience: webmailAudience });
    credentials.push(session.credential);
  }

  assert.equal(verifyWebmailCredential(mailbox.address, credentials[0]), null);
  for (const credential of credentials.slice(1)) {
    assert.ok(verifyWebmailCredential(mailbox.address, credential));
  }
  assert.equal(database.prepare(`
    SELECT COUNT(*) AS count
    FROM webmail_sessions
    WHERE exchanged_at IS NOT NULL AND revoked_at IS NULL
  `).get().count, 5);

  for (let index = 6; index < 20; index += 1) {
    createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience });
  }
  assert.throws(
    () => createWebmailLoginTicket(owner.id, mailbox.id, { audience: webmailAudience }),
    (error) => error?.code === 'WEBMAIL_TICKET_RATE_LIMIT'
  );

  database.prepare(`
    UPDATE webmail_sessions
    SET ticket_expires_at = '2000-01-01T00:00:00.000Z',
        credential_expires_at = '2000-01-01T00:00:00.000Z',
        revoked_at = COALESCE(revoked_at, '2000-01-01T00:00:00.000Z')
  `).run();
  assert.ok(cleanupWebmailSessions({ retentionSeconds: 0 }) > 0);
  assert.equal(database.prepare('SELECT COUNT(*) AS count FROM webmail_sessions').get().count, 0);
});

function setupMailbox(suffix) {
  const database = initDatabase(
    mkdtempSync(path.join(tmpdir(), `mailhub-webmail-sso-${suffix}-`)),
    `webmail-sso-${suffix}-secret`
  );
  const owner = createUser({
    username: `owner-${suffix}`,
    email: `owner-${suffix}@example.com`,
    password: 'password123'
  });
  createDomain(owner.id, domainFixture(`${suffix}.example`));
  const mailbox = createInboundMailbox(owner.id, {
    address: `inbox@${suffix}.example`,
    password: 'mailbox-password'
  });
  return { database, owner, mailbox };
}

function domainFixture(domain) {
  return {
    domain,
    selector: 'mh',
    verificationToken: `verify-${domain}`,
    dkimPublic: 'public-key',
    dkimPrivate: 'private-key',
    senderHost: `in.${domain}`,
    sendingIp: '192.0.2.10',
    spfExtra: '',
    dmarcPolicy: 'none',
    dmarcRua: ''
  };
}
