import type { FastifyInstance, FastifyReply, FastifyRequest } 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 {
  CreateNoteArtifactSchema,
  ListNoteArtifactsQuerySchema,
  UpdateNoteArtifactSchema,
  type NoteArtifactDoc,
} from './types.js';

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

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

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

    const now = new Date().toISOString();
    const doc: NoteArtifactDoc = {
      id: parsed.data.id,
      productId: PRODUCT_ID,
      workspaceId: parsed.data.workspaceId,
      userId: auth.sub,
      noteId: parsed.data.noteId,
      artifactType: parsed.data.artifactType,
      title: parsed.data.title,
      description: parsed.data.description,
      blobPath: parsed.data.blobPath,
      contentType: parsed.data.contentType,
      sizeBytes: parsed.data.sizeBytes,
      createdAt: now,
      createdBy: auth.sub,
      updatedAt: now,
      updatedBy: auth.sub,
    };

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

  app.patch('/note-artifacts/:id', async (req: FastifyRequest) => {
    const auth = await extractAuth(req);
    const { id } = req.params as { id: string };
    const workspaceId = (req.query as { workspaceId?: string }).workspaceId;

    if (!workspaceId) {
      throw new BadRequestError('workspaceId is required');
    }

    const parsed = UpdateNoteArtifactSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map((issue: { message: string }) => issue.message).join('; '));
    }

    const existing = await repo.getNoteArtifact(id, workspaceId);
    if (!existing || existing.userId !== auth.sub || existing.productId !== PRODUCT_ID) {
      throw new NotFoundError('Note artifact not found');
    }

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

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

    return updated;
  });
}
