/**
 * Court Filing Routes
 * E-filing and court document management
 */

import { FastifyInstance } from 'fastify';
import {
  createCourtFiling,
  getCourtFiling,
  listCourtFilings,
  updateFilingStatus,
  getFilingDeadlines,
} from '@the-order/database';
import { authenticateJWT, requireRole } from '@the-order/shared';

export async function registerFilingRoutes(server: FastifyInstance): Promise<void> {
  server.post('/filings', {
    preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
    schema: {
      body: {
        type: 'object',
        required: ['document_id', 'court_name'],
        properties: {
          document_id: { type: 'string' },
          matter_id: { type: 'string' },
          court_name: { type: 'string' },
          case_number: { type: 'string' },
          filing_type: { type: 'string' },
        },
      },
      tags: ['filings'],
    },
  }, async (request, reply) => {
    const body = request.body as any;
    const user = (request as any).user;
    const filing = await createCourtFiling({ ...body, filed_by: user?.id });
    return reply.code(201).send(filing);
  });

  server.get('/filings/:id', {
    preHandler: [authenticateJWT],
    schema: { params: { type: 'object', properties: { id: { type: 'string' } } }, tags: ['filings'] },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const filing = await getCourtFiling(id);
    if (!filing) return reply.code(404).send({ error: 'Filing not found' });
    return reply.send(filing);
  });

  server.get('/filings', {
    preHandler: [authenticateJWT],
    schema: {
      querystring: {
        type: 'object',
        properties: { matter_id: { type: 'string' }, status: { type: 'string' } },
      },
      tags: ['filings'],
    },
  }, async (request, reply) => {
    const query = request.query as any;
    const filings = await listCourtFilings(query);
    return reply.send({ filings });
  });

  server.get('/matters/:id/filing-deadlines', {
    preHandler: [authenticateJWT],
    schema: { params: { type: 'object', properties: { id: { type: 'string' } } }, tags: ['filings'] },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const deadlines = await getFilingDeadlines(id);
    return reply.send({ deadlines });
  });
}

