/**
 * Letters of Credence endpoints
 */

import { FastifyInstance } from 'fastify';
import { KMSClient } from '@the-order/crypto';
import {
  issueLettersOfCredence,
  trackLettersOfCredenceStatus,
  revokeLettersOfCredence,
} from './letters-of-credence';
import { authenticateJWT, requireRole, getAuthorizationService } from '@the-order/shared';

export async function registerLettersOfCredenceRoutes(
  server: FastifyInstance,
  kmsClient: KMSClient
): Promise<void> {
  // Issue Letters of Credence
  server.post(
    '/diplomatic/letters-of-credence/issue',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'diplomatic-admin')],
      schema: {
        body: {
          type: 'object',
          required: ['recipientDid', 'recipientName', 'recipientTitle', 'missionCountry', 'missionType', 'appointmentDate'],
          properties: {
            recipientDid: { type: 'string' },
            recipientName: { type: 'string' },
            recipientTitle: { type: 'string' },
            missionCountry: { type: 'string' },
            missionType: { type: 'string', enum: ['embassy', 'consulate', 'delegation', 'mission'] },
            appointmentDate: { type: 'string', format: 'date-time' },
            expirationDate: { type: 'string', format: 'date-time' },
            additionalClaims: { type: 'object' },
            useEntraVerifiedID: { type: 'boolean' },
          },
        },
        description: 'Issue Letters of Credence',
        tags: ['diplomatic'],
      },
    },
    async (request, reply) => {
      const body = request.body as {
        recipientDid: string;
        recipientName: string;
        recipientTitle: string;
        missionCountry: string;
        missionType: 'embassy' | 'consulate' | 'delegation' | 'mission';
        appointmentDate: string;
        expirationDate?: string;
        additionalClaims?: Record<string, unknown>;
        useEntraVerifiedID?: boolean;
      };
      const user = (request as any).user;

      // Check authorization
      const authService = getAuthorizationService();
      const credentialType = ['VerifiableCredential', 'DiplomaticCredential', 'LettersOfCredence'];
      const authCheck = await authService.canIssueCredential(user, credentialType);

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

      // Issue Letters of Credence
      const credentialId = await issueLettersOfCredence(
        {
          recipientDid: body.recipientDid,
          recipientName: body.recipientName,
          recipientTitle: body.recipientTitle,
          missionCountry: body.missionCountry,
          missionType: body.missionType,
          appointmentDate: new Date(body.appointmentDate),
          expirationDate: body.expirationDate ? new Date(body.expirationDate) : undefined,
          additionalClaims: body.additionalClaims,
        },
        kmsClient,
        body.useEntraVerifiedID || false
      );

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

  // Track Letters of Credence status
  server.get(
    '/diplomatic/letters-of-credence/:credentialId/status',
    {
      preHandler: [authenticateJWT],
      schema: {
        params: {
          type: 'object',
          properties: {
            credentialId: { type: 'string' },
          },
        },
        description: 'Get Letters of Credence status',
        tags: ['diplomatic'],
      },
    },
    async (request, reply) => {
      const { credentialId } = request.params as { credentialId: string };
      const status = await trackLettersOfCredenceStatus(credentialId);
      return reply.send(status);
    }
  );

  // Revoke Letters of Credence
  server.post(
    '/diplomatic/letters-of-credence/:credentialId/revoke',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'diplomatic-admin')],
      schema: {
        params: {
          type: 'object',
          properties: {
            credentialId: { type: 'string' },
          },
        },
        body: {
          type: 'object',
          required: ['reason'],
          properties: {
            reason: { type: 'string' },
          },
        },
        description: 'Revoke Letters of Credence',
        tags: ['diplomatic'],
      },
    },
    async (request, reply) => {
      const { credentialId } = request.params as { credentialId: string };
      const { reason } = request.body as { reason: string };

      await revokeLettersOfCredence(credentialId, reason);
      return reply.send({ revoked: true });
    }
  );
}

