/**
 * Judicial credential endpoints
 */

import { FastifyInstance } from 'fastify';
import { KMSClient } from '@the-order/crypto';
import { issueJudicialCredential, getJudicialCredentialTemplate, type JudicialRole } from './judicial-credentials';
import { authenticateJWT, requireRole, getAuthorizationService } from '@the-order/shared';

export async function registerJudicialRoutes(
  server: FastifyInstance,
  kmsClient: KMSClient
): Promise<void> {
  // Issue judicial credential
  server.post(
    '/judicial/issue',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'judicial-admin')],
      schema: {
        body: {
          type: 'object',
          required: ['subjectDid', 'role', 'appointmentDate', 'appointmentAuthority'],
          properties: {
            subjectDid: { type: 'string' },
            role: {
              type: 'string',
              enum: [
                'Registrar',
                'JudicialAuditor',
                'ProvostMarshal',
                'Judge',
                'CourtClerk',
                'Bailiff',
                'CourtOfficer',
              ],
            },
            appointmentDate: { type: 'string', format: 'date-time' },
            appointmentAuthority: { type: 'string' },
            jurisdiction: { type: 'string' },
            termLength: { type: 'number' },
            expirationDate: { type: 'string', format: 'date-time' },
            additionalClaims: { type: 'object' },
          },
        },
        description: 'Issue judicial credential',
        tags: ['judicial'],
      },
    },
    async (request, reply) => {
      const body = request.body as {
        subjectDid: string;
        role: JudicialRole;
        appointmentDate: string;
        appointmentAuthority: string;
        jurisdiction?: string;
        termLength?: number;
        expirationDate?: string;
        additionalClaims?: Record<string, unknown>;
      };
      const user = (request as any).user;

      // Check authorization
      const authService = getAuthorizationService();
      const credentialType = ['VerifiableCredential', 'JudicialCredential', `${body.role}Credential`];
      const authCheck = await authService.canIssueCredential(user, credentialType);

      if (!authCheck.allowed) {
        return reply.code(403).send({ error: authCheck.reason || 'Not authorized' });
      }

      // Issue credential
      const credentialId = await issueJudicialCredential(
        body.subjectDid,
        {
          role: body.role,
          appointmentDate: new Date(body.appointmentDate),
          appointmentAuthority: body.appointmentAuthority,
          jurisdiction: body.jurisdiction,
          termLength: body.termLength,
          expirationDate: body.expirationDate ? new Date(body.expirationDate) : undefined,
          additionalClaims: body.additionalClaims,
        },
        kmsClient
      );

      return reply.send({ credentialId });
    }
  );

  // Get judicial credential template
  server.get(
    '/judicial/template/:role',
    {
      preHandler: [authenticateJWT],
      schema: {
        params: {
          type: 'object',
          properties: {
            role: {
              type: 'string',
              enum: [
                'Registrar',
                'JudicialAuditor',
                'ProvostMarshal',
                'Judge',
                'CourtClerk',
                'Bailiff',
                'CourtOfficer',
              ],
            },
          },
        },
        description: 'Get judicial credential template for role',
        tags: ['judicial'],
      },
    },
    async (request, reply) => {
      const { role } = request.params as { role: JudicialRole };
      const template = getJudicialCredentialTemplate(role);
      return reply.send(template);
    }
  );
}

