import type { FastifyInstance } from 'fastify';
import { BadRequestError, NotFoundError } from '../../lib/errors.js';
import { extractAuth } from '../../lib/auth.js';
import { PRODUCT_ID } from '../../lib/product-config.js';
import * as repo from './repository.js';
import {
  CreateWorkspaceSchema,
  ListWorkspacesQuerySchema,
  UpdateWorkspaceSchema,
  type WorkspaceDoc,
} from './types.js';

export async function workspaceRoutes(app: FastifyInstance) {
  app.get('/workspaces', async req => {
    const auth = await extractAuth(req);
    const parsed = ListWorkspacesQuerySchema.safeParse(req.query);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(issue => issue.message).join('; '));
    }

    const result = await repo.listWorkspaces(auth.sub, PRODUCT_ID, parsed.data);
    return { ...result, limit: parsed.data.limit, offset: parsed.data.offset };
  });

  app.get('/workspaces/:id', async req => {
    const auth = await extractAuth(req);
    const { id } = req.params as { id: string };
    const workspace = await repo.getWorkspace(id, auth.sub);

    if (!workspace || workspace.productId !== PRODUCT_ID) {
      throw new NotFoundError('Workspace not found');
    }

    return workspace;
  });

  app.post('/workspaces', async (req, reply) => {
    const auth = await extractAuth(req);
    const parsed = CreateWorkspaceSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(issue => issue.message).join('; '));
    }

    const now = new Date().toISOString();
    const doc: WorkspaceDoc = {
      id: parsed.data.id,
      productId: PRODUCT_ID,
      userId: auth.sub,
      name: parsed.data.name,
      description: parsed.data.description,
      members: [{ userId: auth.sub, role: 'owner' }, ...parsed.data.members.filter(member => member.userId !== auth.sub)],
      createdAt: now,
      updatedAt: now,
      createdBy: auth.sub,
      updatedBy: auth.sub,
    };

    const created = await repo.createWorkspace(doc);
    reply.code(201);
    return created;
  });

  app.patch('/workspaces/:id', async req => {
    const auth = await extractAuth(req);
    const { id } = req.params as { id: string };
    const parsed = UpdateWorkspaceSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map(issue => issue.message).join('; '));
    }

    const existing = await repo.getWorkspace(id, auth.sub);
    if (!existing || existing.productId !== PRODUCT_ID) {
      throw new NotFoundError('Workspace not found');
    }

    const updated = await repo.updateWorkspace(id, auth.sub, {
      ...parsed.data,
      updatedAt: new Date().toISOString(),
      updatedBy: auth.sub,
    });

    if (!updated) {
      throw new NotFoundError('Workspace not found');
    }

    return updated;
  });
}
