import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
  CreateMedicinePriceRecordSchema,
  MedicinePriceHistoryQuerySchema,
  MedicinePriceAnalyticsQuerySchema,
  MedicinePriceRecordResponseSchema,
  MedicinePriceHistoryResponseSchema,
  StoreComparisonResponseSchema,
  MedicineSpendingAnalyticsResponseSchema,
} from '@meshitrack/shared';
import { MedicinePricesRepository } from './medicine-prices.repository.js';
import { MedicinePricesService } from './medicine-prices.service.js';

type AnyPriceDoc = {
  _id: string | { toString: () => string };
  householdId: string;
  medicineProductId: string;
  medicineProductBrand: string;
  medicineId: string;
  medicineName: string;
  storeId: string;
  storeName: string;
  price: number;
  currency: string;
  quantity: number;
  unit: string;
  pricePerUnit: number;
  date: Date | string | { toISOString: () => string };
  isInsurancePrice: boolean;
  notes?: string;
  createdBy: string;
  createdAt: Date | string | { toISOString: () => string };
};

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

function toPriceRecordResponse(rawDoc: unknown) {
  const doc = rawDoc as AnyPriceDoc;
  return {
    _id: typeof doc._id === 'string' ? doc._id : doc._id.toString(),
    householdId: doc.householdId,
    medicineProductId: doc.medicineProductId,
    medicineProductBrand: doc.medicineProductBrand,
    medicineId: doc.medicineId,
    medicineName: doc.medicineName,
    storeId: doc.storeId,
    storeName: doc.storeName,
    price: doc.price,
    currency: doc.currency,
    quantity: doc.quantity,
    unit: doc.unit,
    pricePerUnit: doc.pricePerUnit,
    date: toIso(doc.date),
    isInsurancePrice: doc.isInsurancePrice,
    ...(doc.notes != null ? { notes: doc.notes } : {}),
    createdBy: doc.createdBy,
    createdAt: toIso(doc.createdAt),
  };
}

declare module '@fastify/awilix' {
  interface Cradle {
    medicinePricesRepository: MedicinePricesRepository;
    medicinePricesService: MedicinePricesService;
  }
}

export default fp(
  async (fastify) => {
    fastify.diContainer.register({
      medicinePricesRepository: asClass(MedicinePricesRepository, { lifetime: Lifetime.SINGLETON }),
      medicinePricesService: asClass(MedicinePricesService, { lifetime: Lifetime.SINGLETON }),
    });

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

    app.route({
      method: 'POST',
      url: '/api/v1/households/:householdId/medicine-prices',
      schema: {
        params: householdParams,
        body: CreateMedicinePriceRecordSchema,
        response: { 201: MedicinePriceRecordResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinePricesService');
        const record = await service.recordPrice(
          request.body,
          request.params.householdId,
          request.user.keycloakId,
        );
        return reply.status(201).send(toPriceRecordResponse(record));
      },
    });

    app.route({
      method: 'GET',
      url: '/api/v1/households/:householdId/medicine-prices/history/:medicineId',
      schema: {
        params: householdParams.extend({ medicineId: z.string() }),
        querystring: MedicinePriceHistoryQuerySchema,
        response: { 200: MedicinePriceHistoryResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinePricesService');
        const result = await service.getPriceHistory(
          request.params.householdId,
          request.params.medicineId,
          request.query,
        );
        return reply.send({
          data: result.data.map(toPriceRecordResponse),
          pagination: result.pagination,
        });
      },
    });

    app.route({
      method: 'GET',
      url: '/api/v1/households/:householdId/medicine-prices/compare/:medicineId',
      schema: {
        params: householdParams.extend({ medicineId: z.string() }),
        response: { 200: StoreComparisonResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinePricesService');
        const results = await service.compareStores(
          request.params.householdId,
          request.params.medicineId,
        );
        return reply.send({
          data: results.map((r) => ({
            ...r,
            date: toIso(r.date),
          })),
        });
      },
    });

    app.route({
      method: 'GET',
      url: '/api/v1/households/:householdId/medicine-prices/analytics',
      schema: {
        params: householdParams,
        querystring: MedicinePriceAnalyticsQuerySchema,
        response: { 200: MedicineSpendingAnalyticsResponseSchema },
      },
      handler: async (request, reply) => {
        const service = fastify.diContainer.resolve('medicinePricesService');
        const analytics = await service.getAnalytics(request.params.householdId, request.query);
        return reply.send(analytics);
      },
    });
  },
  {
    name: 'medicine-prices-routes',
    dependencies: ['auth-plugin'],
  },
);
