/**
 * Status Endpoint
 * Get credential status by resident number
 */

import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { query } from '@the-order/database';

/**
 * Register status endpoint
 */
export async function registerStatusEndpoint(server: FastifyInstance): Promise<void> {
  // Get credential status by resident number
  server.get(
    '/status/:residentNumber',
    {
      schema: {
        params: {
          type: 'object',
          required: ['residentNumber'],
          properties: {
            residentNumber: { type: 'string' },
          },
        },
        description: 'Get credential status by resident number',
        tags: ['status'],
        response: {
          200: {
            type: 'object',
            properties: {
              residentNumber: { type: 'string' },
              status: { type: 'string', enum: ['active', 'suspended', 'revoked', 'expired'] },
              issuedAt: { type: 'string', format: 'date-time' },
              expiresAt: { type: 'string', format: 'date-time' },
              credentialId: { type: 'string' },
            },
          },
        },
      },
    },
    async (request: FastifyRequest, reply: FastifyReply) => {
      const { residentNumber } = request.params as { residentNumber: string };

      try {
        // Find credential by resident number in credential subject
        const result = await query<{
          credential_id: string;
          credential_subject: unknown;
          issuance_date: Date;
          expiration_date: Date | null;
          revoked: boolean;
        }>(
          `SELECT credential_id, credential_subject, issuance_date, expiration_date, revoked
           FROM verifiable_credentials
           WHERE credential_subject->>'residentNumber' = $1
           ORDER BY issuance_date DESC
           LIMIT 1`,
          [residentNumber]
        );

        if (!result.rows[0]) {
          return reply.code(404).send({
            error: 'Credential not found',
          });
        }

        const row = result.rows[0]!;
        const credentialSubject = row.credential_subject as { residentNumber?: string };
        const now = new Date();
        const expiresAt = row.expiration_date;

        let status: 'active' | 'suspended' | 'revoked' | 'expired';
        if (row.revoked) {
          status = 'revoked';
        } else if (expiresAt && new Date(expiresAt) < now) {
          status = 'expired';
        } else {
          status = 'active';
        }

        return reply.send({
          residentNumber: credentialSubject.residentNumber || residentNumber,
          status,
          issuedAt: row.issuance_date.toISOString(),
          expiresAt: expiresAt ? expiresAt.toISOString() : null,
          credentialId: row.credential_id,
        });
      } catch (error) {
        return reply.code(500).send({
          error: 'Failed to get status',
          message: error instanceof Error ? error.message : String(error),
        });
      }
    }
  );
}

