import jwt, { SignOptions } from 'jsonwebtoken';
import type { Role } from '@prisma/client';
import { env } from '../config/env';
import { UnauthorizedError } from './errors';

/** Claims embedded in the access token — enough to authorize without a DB hit. */
export interface AccessTokenPayload {
  sub: string; // userId
  role: Role;
  tenantId: string | null;
  /** Issued-at, stamped by jsonwebtoken on sign. Absent only on payloads we build ourselves. */
  iat?: number;
}

interface RefreshTokenPayload {
  sub: string;
  type: 'refresh';
  /** Issued-at, stamped by jsonwebtoken. Used to reject pre-password-change tokens. */
  iat?: number;
}

export function signAccessToken(payload: Omit<AccessTokenPayload, 'iat'>): string {
  return jwt.sign(payload, env.JWT_ACCESS_SECRET, {
    expiresIn: env.JWT_ACCESS_EXPIRES_IN,
  } as SignOptions);
}

export function signRefreshToken(userId: string): string {
  return jwt.sign({ sub: userId, type: 'refresh' } satisfies RefreshTokenPayload, env.JWT_REFRESH_SECRET, {
    expiresIn: env.JWT_REFRESH_EXPIRES_IN,
  } as SignOptions);
}

export function verifyAccessToken(token: string): AccessTokenPayload {
  try {
    const decoded = jwt.verify(token, env.JWT_ACCESS_SECRET) as AccessTokenPayload;
    return decoded;
  } catch {
    throw new UnauthorizedError('Invalid or expired access token');
  }
}

export function verifyRefreshToken(token: string): RefreshTokenPayload {
  try {
    const decoded = jwt.verify(token, env.JWT_REFRESH_SECRET) as RefreshTokenPayload;
    if (decoded.type !== 'refresh') throw new Error('wrong token type');
    return decoded;
  } catch {
    throw new UnauthorizedError('Invalid or expired refresh token');
  }
}
