import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import {
  createTextMemoNote,
  deleteTextMemoNote,
  importTextMemoNotes,
  listTextMemoNotes,
  textMemoNoteCreateSchema,
  textMemoNoteImportSchema,
  textMemoNoteUpdateSchema,
  updateTextMemoLayoutFeatureDescription,
  updateTextMemoNote,
} from '../services/text-memo-service.js';

function resolveClientId(headers: Record<string, unknown>) {
  return String(headers['x-client-id'] ?? '').trim();
}

export async function registerTextMemoRoutes(app: FastifyInstance) {
  app.get('/api/text-memo/notes', async (request) => {
    await updateTextMemoLayoutFeatureDescription().catch(() => false);
    const items = await listTextMemoNotes(resolveClientId(request.headers));
    return {
      ok: true,
      items,
    };
  });

  app.post('/api/text-memo/notes', async (request) => {
    const payload = textMemoNoteCreateSchema.parse(request.body ?? {});
    const item = await createTextMemoNote(resolveClientId(request.headers), payload);
    await updateTextMemoLayoutFeatureDescription().catch(() => false);

    return {
      ok: true,
      item,
    };
  });

  app.post('/api/text-memo/notes/import', async (request) => {
    const payload = textMemoNoteImportSchema.parse(request.body ?? {});
    const items = await importTextMemoNotes(resolveClientId(request.headers), payload);
    await updateTextMemoLayoutFeatureDescription().catch(() => false);

    return {
      ok: true,
      items,
    };
  });

  app.put('/api/text-memo/notes/:noteId', async (request, reply) => {
    const noteId = z.string().trim().min(1).parse((request.params as { noteId: string }).noteId);
    const payload = textMemoNoteUpdateSchema.parse(request.body ?? {});
    const item = await updateTextMemoNote(resolveClientId(request.headers), noteId, payload);

    if (!item) {
      return reply.code(404).send({
        message: '수정할 메모를 찾을 수 없습니다.',
      });
    }

    await updateTextMemoLayoutFeatureDescription().catch(() => false);

    return {
      ok: true,
      item,
    };
  });

  app.delete('/api/text-memo/notes/:noteId', async (request, reply) => {
    const noteId = z.string().trim().min(1).parse((request.params as { noteId: string }).noteId);
    const deleted = await deleteTextMemoNote(resolveClientId(request.headers), noteId);

    if (!deleted) {
      return reply.code(404).send({
        message: '삭제할 메모를 찾을 수 없습니다.',
      });
    }

    await updateTextMemoLayoutFeatureDescription().catch(() => false);

    return {
      ok: true,
    };
  });
}
