import { Hono } from 'hono';
import { CreateWebhookSchema } from '../types/index';

export const webhooksRouter = new Hono();

// In-memory webhook store (will be DB-backed later)
const webhooks: Array<{
  id: string;
  url: string;
  events: string[];
  secret?: string;
  active: boolean;
  createdAt: string;
}> = [];

// ─── GET /v1/webhooks ───────────────────────────────────
webhooksRouter.get('/', async (c) => {
  return c.json({ success: true, data: webhooks });
});

// ─── GET /v1/webhooks/events ────────────────────────────
webhooksRouter.get('/events', async (c) => {
  return c.json({
    success: true,
    data: [
      'pipeline.created', 'pipeline.stage_changed', 'pipeline.completed', 'pipeline.failed',
      'task.created', 'task.completed', 'task.sla_warning', 'task.sla_breached',
      'approval.pending', 'approval.approved', 'approval.rejected',
      'agent.status_changed',
      'deploy.started', 'deploy.succeeded', 'deploy.failed',
      'asset.created',
    ],
  });
});

// ─── POST /v1/webhooks ──────────────────────────────────
webhooksRouter.post('/', async (c) => {
  try {
    const body = CreateWebhookSchema.parse(await c.req.json());
    const webhook = {
      id: `wh_${Date.now().toString(36)}`,
      url: body.url,
      events: body.events,
      secret: body.secret,
      active: true,
      createdAt: new Date().toISOString(),
    };
    webhooks.push(webhook);
    return c.json({ success: true, data: { ...webhook, secret: undefined } }, 201);
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } }, 400);
    }
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── DELETE /v1/webhooks/:id ────────────────────────────
webhooksRouter.delete('/:id', async (c) => {
  const idx = webhooks.findIndex((w) => w.id === c.req.param('id'));
  if (idx === -1) return c.json({ success: false, error: { code: 'NOT_FOUND', message: 'Webhook not found' } }, 404);
  webhooks.splice(idx, 1);
  return c.json({ success: true, data: { deleted: true } });
});
