import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
  CreateMedicineSchema,
  UpdateMedicineSchema,
  MedicineQuerySchema,
  MedicineResponseSchema,
  MedicineListResponseSchema,
} from '@meshitrack/shared';
import { MedicinesRepository } from './medicines.repository.js';
import { MedicinesService } from './medicines.service.js';

type AnyMedicineDoc = {
  _id: string | { toString: () => string };
  householdId: string;
  name: string;
  form: string;
  strength: number;
  strengthUnit: string;
  category: string;
  notes?: string | null;
  tags: string[];
  createdBy: string;
  createdAt: string | { toISOString: () => string };
  updatedAt: string | { toISOString: () => string };
};

function toStr(v: string | { toString: () => string }): string {
  return typeof v === 'string' ? v : v.toString();
}

function toIso(v: string | { toISOString: () => string }): string {
  return typeof v === 'string' ? v : v.toISOString();
}

function toMedicineResponse(doc: AnyMedicineDoc): z.infer<typeof MedicineResponseSchema> {
  return {
    _id: toStr(doc._id),
    householdId: doc.householdId,
    name: doc.name,
    form: doc.form,
    strength: doc.strength,
    strengthUnit: doc.strengthUnit,
    category: doc.category,
    ...(doc.notes ? { notes: doc.notes } : {}),
    tags: doc.tags,
    createdBy: doc.createdBy,
    createdAt: toIso(doc.createdAt),
    updatedAt: toIso(doc.updatedAt),
  };
}

declare module '@fastify/awilix' {
  interface Cradle {
    medicinesRepository: MedicinesRepository;
    medicinesService: MedicinesService;
  }
}

export default fp(
  async (fastify) => {
    fastify.diContainer.register({
      medicinesRepository: asClass(MedicinesRepository, { lifetime: Lifetime.SINGLETON }),
      medicinesService: asClass(MedicinesService, { lifetime: Lifetime.SINGLETON }),
    });

    const app = fastify.withTypeProvider<ZodTypeProvider>();
    const householdParams = z.object({ householdId: z.string() });

    // GET /api/v1/households/:householdId/medicines — list/search
    app.route({
      method: 'GET',
      url: '/api/v1/households/:householdId/medicines',
      schema: {
        params: householdParams,
        querystring: MedicineQuerySchema,
        response: { 200: MedicineListResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinesService');
        const result = await service.list(request.params.householdId, request.query);
        return reply.send({
          data: result.data.map(toMedicineResponse),
          pagination: result.pagination,
        });
      },
    });

    // GET /api/v1/households/:householdId/medicines/:id — get by id
    app.route({
      method: 'GET',
      url: '/api/v1/households/:householdId/medicines/:id',
      schema: {
        params: householdParams.extend({ id: z.string() }),
        response: { 200: MedicineResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinesService');
        const medicine = await service.getById(request.params.id, request.params.householdId);
        return reply.send(toMedicineResponse(medicine));
      },
    });

    // POST /api/v1/households/:householdId/medicines — create
    app.route({
      method: 'POST',
      url: '/api/v1/households/:householdId/medicines',
      schema: {
        params: householdParams,
        body: CreateMedicineSchema,
        response: { 201: MedicineResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinesService');
        const medicine = await service.create(
          request.body,
          request.params.householdId,
          request.user.keycloakId,
        );
        return reply.status(201).send(toMedicineResponse(medicine));
      },
    });

    // PATCH /api/v1/households/:householdId/medicines/:id — update
    app.route({
      method: 'PATCH',
      url: '/api/v1/households/:householdId/medicines/:id',
      schema: {
        params: householdParams.extend({ id: z.string() }),
        body: UpdateMedicineSchema,
        response: { 200: MedicineResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinesService');
        const medicine = await service.update(
          request.params.id,
          request.params.householdId,
          request.body,
        );
        return reply.send(toMedicineResponse(medicine));
      },
    });

    // DELETE /api/v1/households/:householdId/medicines/:id — soft delete
    app.route({
      method: 'DELETE',
      url: '/api/v1/households/:householdId/medicines/:id',
      schema: {
        params: householdParams.extend({ id: z.string() }),
        response: { 204: z.undefined() },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinesService');
        await service.delete(request.params.id, request.params.householdId);
        return reply.status(204).send();
      },
    });
  },
  {
    name: 'medicines-routes',
    dependencies: ['auth-plugin'],
  },
);
