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

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

// GET /webhooks — 列出所有 Webhooks（需要授權標頭）
webhooksListRouter.get('/webhooks', async (c) => {
  const authHeader = c.req.header('Authorization');
  if (!authHeader) {
    return c.json({ error: 'unauthorized: missing Authorization header' }, 401);
  }

  const list = await c.env.WEBHOOKS.list();
  const webhooks = [];

  for (const key of list.keys) {
    const raw = await c.env.WEBHOOKS.get(key.name, 'text');
    if (!raw) continue;

    const record = await validateAndParseWebhook(raw);
    if (!record) continue;

    webhooks.push({
      token: key.name,
      description: record.description,
      created_at: record.created_at,
    });
  }

  return c.json({ webhooks, total: webhooks.length });
});
