/**
 * Document Workflow Routes
 * Approval, signing, and review workflows
 */

import { FastifyInstance } from 'fastify';
import {
  createDocumentWorkflow,
  getDocumentWorkflow,
  listDocumentWorkflows,
  updateWorkflowStatus,
  assignWorkflowStep,
  completeWorkflowStep,
} from '@the-order/database';
import { authenticateJWT, requireRole } from '@the-order/shared';

export async function registerWorkflowRoutes(server: FastifyInstance): Promise<void> {
  server.post('/workflows', {
    preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
    schema: {
      body: {
        type: 'object',
        required: ['document_id', 'workflow_type'],
        properties: {
          document_id: { type: 'string' },
          workflow_type: { type: 'string' },
          steps: { type: 'array' },
        },
      },
      tags: ['workflows'],
    },
  }, async (request, reply) => {
    const body = request.body as any;
    const user = (request as any).user;
    const workflow = await createDocumentWorkflow({
      ...body,
      created_by: user?.id,
    });
    return reply.code(201).send(workflow);
  });

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

  server.get('/documents/:id/workflows', {
    preHandler: [authenticateJWT],
    schema: { params: { type: 'object', properties: { id: { type: 'string' } } }, tags: ['workflows'] },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const workflows = await listDocumentWorkflows(id);
    return reply.send({ workflows });
  });

  server.patch('/workflows/:id/status', {
    preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
    schema: {
      params: { type: 'object', properties: { id: { type: 'string' } } },
      body: { type: 'object', required: ['status'], properties: { status: { type: 'string' } } },
      tags: ['workflows'],
    },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const { status } = request.body as { status: string };
    const workflow = await updateWorkflowStatus(id, status);
    if (!workflow) return reply.code(404).send({ error: 'Workflow not found' });
    return reply.send(workflow);
  });
}

