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 {
  CreateNoteAgentActionSchema,
  ListNoteAgentActionsQuerySchema,
  UpdateNoteAgentActionSchema,
  type NoteAgentActionDoc,
} from './types.js';

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

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

  app.post('/note-agent-actions', async (req: FastifyRequest, reply: FastifyReply) => {
    const auth = await extractAuth(req);
    const parsed = CreateNoteAgentActionSchema.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: NoteAgentActionDoc = {
      id: parsed.data.id,
      productId: PRODUCT_ID,
      workspaceId: parsed.data.workspaceId,
      userId: auth.sub,
      noteId: parsed.data.noteId,
      actorId: parsed.data.actorId,
      actorType: parsed.data.actorType,
      toolName: parsed.data.toolName,
      actionType: parsed.data.actionType,
      state: parsed.data.state,
      reason: parsed.data.reason,
      beforeSummary: parsed.data.beforeSummary,
      afterSummary: parsed.data.afterSummary,
      idempotencyKey: parsed.data.idempotencyKey,
      correlationId: parsed.data.correlationId,
      workflowId: parsed.data.workflowId,
      createdAt: now,
      updatedAt: now,
      createdBy: auth.sub,
      updatedBy: auth.sub,
    };

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

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

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

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

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

    return updated;
  });
}
