import type { FastifyInstance } from 'fastify';
import { BadRequestError } 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 {
  CreateNoteRelationshipSchema,
  ListNoteRelationshipsQuerySchema,
  type NoteRelationshipDoc,
} from './types.js';

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

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

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

    const now = new Date().toISOString();
    const doc: NoteRelationshipDoc = {
      id: parsed.data.id,
      productId: PRODUCT_ID,
      workspaceId: parsed.data.workspaceId,
      userId: auth.sub,
      fromNoteId: parsed.data.fromNoteId,
      toNoteId: parsed.data.toNoteId,
      relationshipType: parsed.data.relationshipType,
      createdAt: now,
      createdBy: auth.sub,
      updatedAt: now,
      updatedBy: auth.sub,
    };

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