import { Hono } from 'hono';
import type { Bindings } from '../types';
import { validateAndParseWebhook } from '../actions/webhook-handlers';

export const webhooksCrudRouter = new Hono<{ Bindings: Bindings }>();

type WebhookRecord = {
  graph: Record<string, unknown>;
  description: string;
  created_at: string;
};

// GET /webhooks/:token — 查詢 Webhook 基本資訊
webhooksCrudRouter.get('/webhooks/:token', async (c) => {
  const token = c.req.param('token');
  const raw = await c.env.WEBHOOKS.get(token, 'text');
  if (!raw) return c.json({ error: 'not found' }, 404);

  const record = await validateAndParseWebhook(raw);
  if (!record) return c.json({ error: '資料損毀' }, 500);

  return c.json({
    token,
    description: record.description,
    created_at: record.created_at,
  });
});

// PUT /webhooks/:token — 更新 Webhook 定義
webhooksCrudRouter.put('/webhooks/:token', async (c) => {
  const token = c.req.param('token');
  if (!token || token.length < 16) {
    return c.json({ error: 'invalid token' }, 400);
  }

  const raw = await c.env.WEBHOOKS.get(token, 'text');
  if (!raw) return c.json({ error: 'webhook not found' }, 404);

  const existing = await validateAndParseWebhook(raw);
  if (!existing) return c.json({ error: 'webhook 定義損毀' }, 500);

  const body = await c.req.json().catch(() => null);
  if (!body) return c.json({ error: 'invalid json' }, 400);

  const updatedRecord: WebhookRecord = {
    graph: existing.graph,
    description: existing.description,
    created_at: existing.created_at,
  };

  if (body.description !== undefined) {
    updatedRecord.description = typeof body.description === 'string' ? body.description : existing.description;
  }

  if (body.graph !== undefined) {
    updatedRecord.graph = body.graph;
  }

  await c.env.WEBHOOKS.put(token, JSON.stringify(updatedRecord));

  const baseUrl = new URL(c.req.url).origin;
  return c.json({
    token,
    webhook_url: `${baseUrl}/webhooks/${token}/trigger`,
    description: updatedRecord.description,
    created_at: updatedRecord.created_at,
    updated: true,
  });
});

// DELETE /webhooks/:token — 刪除 Webhook
webhooksCrudRouter.delete('/webhooks/:token', async (c) => {
  const token = c.req.param('token');
  if (!token || token.length < 16) {
    return c.json({ error: 'invalid token' }, 400);
  }

  const existing = await c.env.WEBHOOKS.get(token, 'text');
  if (!existing) return c.json({ error: 'webhook not found' }, 404);

  await c.env.WEBHOOKS.delete(token);
  return c.json({ deleted: true, token });
});
