import type { FastifyApp } from '@bytelyst/fastify-core';
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 {
  CreateNoteTaskSchema,
  ListNoteTasksQuerySchema,
  UpdateNoteTaskSchema,
  type NoteTaskDoc,
} from './types.js';

type RouteApp = Omit<FastifyApp, 'setReadyState' | 'isReadyState'>;

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

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

  app.post('/note-tasks', async (req, reply) => {
    const auth = await extractAuth(req);
    const parsed = CreateNoteTaskSchema.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: NoteTaskDoc = {
      id: parsed.data.id,
      productId: PRODUCT_ID,
      workspaceId: parsed.data.workspaceId,
      userId: auth.sub,
      noteId: parsed.data.noteId,
      title: parsed.data.title,
      description: parsed.data.description,
      status: 'open',
      dueAt: parsed.data.dueAt,
      source: parsed.data.source,
      createdAt: now,
      createdBy: auth.sub,
      updatedAt: now,
      updatedBy: auth.sub,
    };

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

  app.patch('/note-tasks/:id', async req => {
    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 = UpdateNoteTaskSchema.safeParse(req.body);
    if (!parsed.success) {
      throw new BadRequestError(parsed.error.issues.map((issue: { message: string }) => issue.message).join('; '));
    }

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

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

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

    return updated;
  });
}
