import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
import { DosageUnit, MedicineProductSource } from '@meshitrack/shared';

vi.mock('jose', () => ({
  createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
  jwtVerify: vi.fn().mockResolvedValue({
    payload: {
      sub: 'kc-1',
      email: 'test@example.com',
      preferred_username: 'testuser',
      realm_access: { roles: ['member'] },
      householdIds: ['hh1'],
    },
    protectedHeader: { alg: 'RS256' },
    key: {},
  }),
}));

const {
  mockFindByMedicine,
  mockFindById,
  mockCreate,
  mockUpdate,
  mockSoftDelete,
  mockMedicineFindById,
} = vi.hoisted(() => ({
  mockFindByMedicine: vi.fn(),
  mockFindById: vi.fn(),
  mockCreate: vi.fn(),
  mockUpdate: vi.fn(),
  mockSoftDelete: vi.fn(),
  mockMedicineFindById: vi.fn(),
}));

vi.mock('../../../src/modules/medicine-products/medicine-products.repository.js', () => ({
  MedicineProductsRepository: class {
    findByMedicine = mockFindByMedicine;
    findById = mockFindById;
    create = mockCreate;
    update = mockUpdate;
    softDelete = mockSoftDelete;
  },
}));

vi.mock('../../../src/modules/medicines/medicines.repository.js', () => ({
  MedicinesRepository: class {
    findById = mockMedicineFindById;
  },
}));

vi.mock('../../../src/modules/users/users.repository.js', () => ({
  UsersRepository: class {
    findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
    upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
  },
}));

import authPlugin from '../../../src/plugins/auth.plugin.js';
import householdPlugin from '../../../src/plugins/household.plugin.js';
import usersRoutes from '../../../src/modules/users/users.routes.js';
import medicinesRoutes from '../../../src/modules/medicines/medicines.routes.js';
import medicineProductsRoutes from '../../../src/modules/medicine-products/medicine-products.routes.js';

function makeFakeProduct(overrides = {}) {
  return {
    _id: 'mp-1',
    householdId: 'hh1',
    medicineId: 'med-1',
    medicineName: 'Metformin',
    brand: 'CVS Health',
    packageSize: 90,
    packageUnit: DosageUnit.TABLET,
    source: MedicineProductSource.MANUAL,
    createdBy: 'kc-1',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    ...overrides,
  };
}

describe('medicine-products.routes', () => {
  let app: Awaited<ReturnType<typeof buildTestApp>>;

  async function buildTestApp() {
    const instance = Fastify({ logger: false });
    instance.setValidatorCompiler(validatorCompiler);
    instance.setSerializerCompiler(serializerCompiler);
    await instance.register(fastifyAwilixPlugin, {
      disposeOnClose: true,
      disposeOnResponse: true,
      strictBooleanEnforced: true,
    });
    await instance.register(authPlugin);
    await instance.register(householdPlugin);
    await instance.register(usersRoutes);
    await instance.register(medicinesRoutes);
    await instance.register(medicineProductsRoutes);
    await instance.ready();
    return instance;
  }

  const authHeaders = { authorization: 'Bearer valid-token' };

  beforeEach(async () => {
    vi.clearAllMocks();
    app = await buildTestApp();
  });

  afterEach(async () => {
    if (app) await app.close();
  });

  describe('GET /api/v1/households/:householdId/medicines/:medicineId/products', () => {
    it('returns paginated list', async () => {
      const product = makeFakeProduct();
      mockFindByMedicine.mockResolvedValue({
        data: [product],
        pagination: { cursor: null, hasMore: false },
      });

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/medicines/med-1/products',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data).toHaveLength(1);
      expect(body.data[0].brand).toBe('CVS Health');
      expect(body.pagination.hasMore).toBe(false);
    });

    it('handles ObjectId and Date objects in response', async () => {
      const product = makeFakeProduct({
        _id: { toString: () => 'mp-obj' },
        createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
        updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
        manufacturer: 'Pfizer',
        imageUrl: 'https://example.com/img.png',
        notes: 'Store in cool place',
      });
      mockFindByMedicine.mockResolvedValue({
        data: [product],
        pagination: { cursor: null, hasMore: false },
      });

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/medicines/med-1/products',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data[0]._id).toBe('mp-obj');
      expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
      expect(body.data[0].manufacturer).toBe('Pfizer');
      expect(body.data[0].imageUrl).toBe('https://example.com/img.png');
      expect(body.data[0].notes).toBe('Store in cool place');
    });
  });

  describe('GET /api/v1/households/:householdId/medicine-products/:id', () => {
    it('returns a product', async () => {
      mockFindById.mockResolvedValue(makeFakeProduct());

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/medicine-products/mp-1',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      expect(res.json().brand).toBe('CVS Health');
    });

    it('includes concentration fields in response when present', async () => {
      mockFindById.mockResolvedValue(
        makeFakeProduct({ concentration: 5, concentrationUnit: 'mg/ml' }),
      );

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/medicine-products/mp-1',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      expect(res.json().concentration).toBe(5);
      expect(res.json().concentrationUnit).toBe('mg/ml');
    });
  });

  describe('POST /api/v1/households/:householdId/medicines/:medicineId/products', () => {
    it('creates a product', async () => {
      mockMedicineFindById.mockResolvedValue({ _id: 'med-1', name: 'Metformin' });
      mockCreate.mockResolvedValue(makeFakeProduct());

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/medicines/med-1/products',
        headers: authHeaders,
        payload: {
          brand: 'CVS Health',
          packageSize: 90,
          packageUnit: DosageUnit.TABLET,
        },
      });

      expect(res.statusCode).toBe(201);
      expect(res.json().brand).toBe('CVS Health');
    });
  });

  describe('PATCH /api/v1/households/:householdId/medicine-products/:id', () => {
    it('updates a product', async () => {
      mockFindById.mockResolvedValue(makeFakeProduct());
      mockUpdate.mockResolvedValue(makeFakeProduct({ brand: 'Updated' }));

      const res = await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/medicine-products/mp-1',
        headers: authHeaders,
        payload: { brand: 'Updated' },
      });

      expect(res.statusCode).toBe(200);
      expect(res.json().brand).toBe('Updated');
    });
  });

  describe('DELETE /api/v1/households/:householdId/medicine-products/:id', () => {
    it('soft deletes a product', async () => {
      mockFindById.mockResolvedValue(makeFakeProduct());
      mockSoftDelete.mockResolvedValue(makeFakeProduct({ isDeleted: true }));

      const res = await app.inject({
        method: 'DELETE',
        url: '/api/v1/households/hh1/medicine-products/mp-1',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(204);
    });
  });
});
