import type { AuthEngine } from '@platform-modules/auth';
import { createCustomEngine } from '@platform-modules/auth/engine-custom';
import type { TransactionalDatabase } from '@platform-modules/db';
import { customAuthSchema } from '@platform-modules/auth/engine-custom';
import { getDb, type DbEnv } from './db.js';

export type AuthEnv = DbEnv & {
  AUTH_SECRET?: string;
};

export class AuthSecretMissingError extends Error {
  readonly name = 'AuthSecretMissingError';
  constructor() {
    super('AUTH_SECRET is required and must be at least 16 characters. Set it via: wrangler secret put AUTH_SECRET');
  }
}

function resolveAuthSecret(env: AuthEnv): string {
  const secret = env.AUTH_SECRET?.trim();
  if (secret && secret.length >= 16) return secret;
  throw new AuthSecretMissingError();
}

export function buildAuthEngine(env: AuthEnv): AuthEngine {
  const secret = resolveAuthSecret(env);
  const { db } = getDb(env);
  return createCustomEngine({
    db: db as unknown as TransactionalDatabase<typeof customAuthSchema>,
    jwtSecrets: [secret],
    pepper: { currentVersion: 'v1', secrets: { v1: secret } },
  });
}
