import type { FastifyInstance, FastifyRequest } from 'fastify';
import { BadRequestError, NotFoundError } from '@bytelyst/errors';
import { PRODUCT_ID } from '../../lib/product-config.js';
import { getUserId } from '../../lib/request-context.js';
import { getIpcBridge } from '../../lib/ipc-bridge.js';
import { SessionIdParamsSchema } from './types.js';

function buildAuth(req: FastifyRequest): Record<string, unknown> {
  const userId = getUserId(req);
  const role = (req.jwtPayload as Record<string, unknown> | undefined)?.role ?? 'user';
  return { userId, role, productId: PRODUCT_ID, isPlatformAuth: !!req.jwtPayload };
}

export async function sessionRoutes(app: FastifyInstance) {
  const bridge = getIpcBridge();

  app.get('/api/sessions', async req => {
    if (!bridge.isRunning) {
      return { sessions: [] };
    }

    const resp = await bridge.call('list_sessions', { auth: buildAuth(req) });
    if (resp.error) throw new BadRequestError(resp.error.message);
    return resp.result;
  });

  app.get('/api/sessions/:id', async req => {
    const parsed = SessionIdParamsSchema.safeParse(req.params);
    if (!parsed.success)
      throw new BadRequestError(parsed.error.issues.map(issue => issue.message).join('; '));

    if (!bridge.isRunning) throw new NotFoundError('Session not found');

    const resp = await bridge.call('get_session', {
      auth: buildAuth(req),
      sessionId: parsed.data.id,
    });

    if (resp.error) {
      if (resp.error.code === -32001) throw new NotFoundError('Session not found');
      throw new BadRequestError(resp.error.message);
    }
    return resp.result;
  });

  app.delete('/api/sessions/:id', async req => {
    const parsed = SessionIdParamsSchema.safeParse(req.params);
    if (!parsed.success)
      throw new BadRequestError(parsed.error.issues.map(issue => issue.message).join('; '));

    if (!bridge.isRunning) throw new NotFoundError('Session not found');

    const resp = await bridge.call('delete_session', {
      auth: buildAuth(req),
      sessionId: parsed.data.id,
    });

    if (resp.error) {
      if (resp.error.code === -32001) throw new NotFoundError('Session not found');
      throw new BadRequestError(resp.error.message);
    }
    return resp.result;
  });
}
