import { Hono } from 'hono';
import { ApproveSchema, RejectSchema } from '../types/index';
import * as approvalService from '../services/approval.service';

export const approvalsRouter = new Hono();

// ─── GET /v1/approvals ──────────────────────────────────
approvalsRouter.get('/', async (c) => {
  try {
    const status = c.req.query('status');
    const pipelineId = c.req.query('pipeline_id');
    const items = await approvalService.listApprovals({
      status: status || undefined,
      pipelineId: pipelineId || undefined,
    });
    return c.json({ success: true, data: items });
  } catch (err: any) {
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── GET /v1/approvals/:id ──────────────────────────────
approvalsRouter.get('/:id', async (c) => {
  try {
    const approval = await approvalService.getApproval(c.req.param('id'));
    if (!approval) {
      return c.json({ success: false, error: { code: 'NOT_FOUND', message: 'Approval not found' } }, 404);
    }
    return c.json({ success: true, data: approval });
  } catch (err: any) {
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── POST /v1/approvals/:id/approve ────────────────────
approvalsRouter.post('/:id/approve', async (c) => {
  try {
    const body = ApproveSchema.parse(await c.req.json().catch(() => ({})));
    const auth = c.get('auth');
    const approval = await approvalService.approveGate(c.req.param('id'), auth.userId, {
      notes: body.notes,
      conditions: body.conditions,
    });
    return c.json({ success: true, data: approval });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } }, 400);
    }
    if (err.message.includes('not found')) return c.json({ success: false, error: { code: 'NOT_FOUND', message: err.message } }, 404);
    if (err.message.includes('not pending')) return c.json({ success: false, error: { code: 'CONFLICT', message: err.message } }, 409);
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── POST /v1/approvals/:id/reject ─────────────────────
approvalsRouter.post('/:id/reject', async (c) => {
  try {
    const body = RejectSchema.parse(await c.req.json());
    const auth = c.get('auth');
    const approval = await approvalService.rejectGate(c.req.param('id'), auth.userId, body);
    return c.json({ success: true, data: approval });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } }, 400);
    }
    if (err.message.includes('not found')) return c.json({ success: false, error: { code: 'NOT_FOUND', message: err.message } }, 404);
    if (err.message.includes('not pending')) return c.json({ success: false, error: { code: 'CONFLICT', message: err.message } }, 409);
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── POST /v1/approvals/:id/escalate ────────────────────
approvalsRouter.post('/:id/escalate', async (c) => {
  try {
    const body = await c.req.json();
    const auth = c.get('auth');
    const approval = await approvalService.escalateGate(c.req.param('id'), auth.userId, {
      escalateTo: body.escalate_to,
      reason: body.reason,
    });
    return c.json({ success: true, data: approval });
  } catch (err: any) {
    if (err.message.includes('not found')) return c.json({ success: false, error: { code: 'NOT_FOUND', message: err.message } }, 404);
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});
