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';

function buildHeaders(req: import('fastify').FastifyRequest): Record<string, string> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'x-product-id': PRODUCT_ID,
    'x-request-id': req.id,
  };
  const auth = req.headers.authorization;
  if (typeof auth === 'string') headers.authorization = auth;
  return headers;
}

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

  app.post('/api/push/register', async (req, reply) => {
    const userId = getUserId(req);

    try {
      const res = await fetch(`${platformUrl}/notifications/push/register`, {
        method: 'POST',
        headers: buildHeaders(req),
        body: JSON.stringify({
          userId,
          productId: PRODUCT_ID,
          ...(req.body as Record<string, unknown>),
        }),
      });
      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 push registration');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });

  app.delete('/api/push/register', async (req, reply) => {
    const userId = getUserId(req);

    try {
      const res = await fetch(`${platformUrl}/notifications/push/register`, {
        method: 'DELETE',
        headers: buildHeaders(req),
        body: JSON.stringify({
          userId,
          productId: PRODUCT_ID,
          ...(req.body as Record<string, unknown>),
        }),
      });
      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 push unregistration');
      reply.code(502);
      return { error: 'Platform-service unavailable' };
    }
  });
}
