/**
 * Notification preference proxy routes — forward to platform-service.
 *
 * Lets the Tauri desktop app manage notification preferences
 * and webhook subscriptions via cowork-service.
 */

import type { FastifyInstance } from 'fastify';
import { config } from '../../lib/config.js';
import { PRODUCT_ID } from '../../lib/product-config.js';
import { getUserId } from '../../lib/request-context.js';

export async function notificationRoutes(app: FastifyInstance) {
  const platformUrl = config.PLATFORM_SERVICE_URL;

  // GET /api/notifications/prefs — get current user's notification preferences
  app.get('/api/notifications/prefs', async (req, reply) => {
    const userId = getUserId(req);

    try {
      const res = await fetch(`${platformUrl}/notifications/prefs/${encodeURIComponent(userId)}`, {
        headers: {
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy notification prefs');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });

  // PUT /api/notifications/prefs — update current user's notification preferences
  app.put('/api/notifications/prefs', async (req, reply) => {
    const userId = getUserId(req);

    try {
      const res = await fetch(`${platformUrl}/notifications/prefs/${encodeURIComponent(userId)}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
        body: JSON.stringify(req.body),
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy notification prefs update');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });

  // GET /api/webhooks — list webhook subscriptions for this product
  app.get('/api/webhooks', async (req, reply) => {
    try {
      const res = await fetch(`${platformUrl}/webhooks/subscriptions`, {
        headers: {
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy webhook list');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });

  // POST /api/webhooks — create a webhook subscription
  app.post('/api/webhooks', async (req, reply) => {
    try {
      const res = await fetch(`${platformUrl}/webhooks/subscriptions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
        body: JSON.stringify(req.body),
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      reply.code(201);
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy webhook create');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });

  // DELETE /api/webhooks/:id — delete a webhook subscription
  app.delete('/api/webhooks/:id', async (req, reply) => {
    const { id } = req.params as { id: string };

    try {
      const res = await fetch(`${platformUrl}/webhooks/subscriptions/${encodeURIComponent(id)}`, {
        method: 'DELETE',
        headers: {
          'x-product-id': PRODUCT_ID,
          'x-request-id': req.id,
        },
      });
      if (!res.ok) {
        reply.code(res.status);
        return { error: `Platform returned ${res.status}` };
      }
      return res.json();
    } catch (err) {
      req.log.warn({ err }, 'Failed to proxy webhook delete');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });
}
