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 { DosageFrequency, DosageUnit, StrengthUnit, MedicineForm } 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 { mockList, mockGetById, mockCreate, mockUpdate, mockDelete, mockCalculateBurnRates } =
  vi.hoisted(() => ({
    mockList: vi.fn(),
    mockGetById: vi.fn(),
    mockCreate: vi.fn(),
    mockUpdate: vi.fn(),
    mockDelete: vi.fn(),
    mockCalculateBurnRates: vi.fn(),
  }));

vi.mock('../../../src/modules/regimens/regimens.repository.js', () => ({
  RegimensRepository: class {
    findByHousehold = vi.fn();
    findById = vi.fn();
    findActiveByUser = vi.fn();
    create = vi.fn();
    update = vi.fn();
    softDelete = vi.fn();
    delete = vi.fn();
  },
}));

vi.mock('../../../src/modules/regimens/regimens.service.js', () => ({
  RegimensService: class {
    list = mockList;
    getById = mockGetById;
    create = mockCreate;
    update = mockUpdate;
    delete = mockDelete;
    getActiveByUser = vi.fn();
    calculateBurnRates = mockCalculateBurnRates;
  },
}));

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 regimensRoutes from '../../../src/modules/regimens/regimens.routes.js';

function makeFakeRegimen(overrides = {}) {
  return {
    _id: 'reg-1',
    householdId: 'hh1',
    userId: 'kc-1',
    name: 'Daily Medications',
    isActive: true,
    medications: [
      {
        medicineId: 'med-1',
        medicineName: 'Metformin',
        medicineStrength: 500,
        medicineStrengthUnit: StrengthUnit.MG,
        medicineForm: MedicineForm.TABLET,
        dosage: 1,
        dosageUnit: DosageUnit.TABLET,
        frequency: DosageFrequency.DAILY,
        customFrequencyPerDay: null,
        timeOfDay: null,
        instructions: null,
      },
    ],
    createdBy: 'kc-1',
    createdAt: '2024-06-01T00:00:00.000Z',
    updatedAt: '2024-06-01T00:00:00.000Z',
    ...overrides,
  };
}

const validPostBody = {
  name: 'Daily Medications',
  isActive: true,
  medications: [
    {
      medicineId: 'med-1',
      dosage: 1,
      dosageUnit: 'tablet',
      frequency: 'daily',
    },
  ],
};

describe('regimens.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(regimensRoutes);
    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/regimens', () => {
    it('returns paginated list of regimens', async () => {
      const regimen = makeFakeRegimen();
      mockList.mockResolvedValue({
        data: [regimen],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data).toHaveLength(1);
      expect(body.data[0].name).toBe('Daily Medications');
      expect(body.data[0].isActive).toBe(true);
      expect(body.pagination.hasMore).toBe(false);
    });

    it('handles ObjectId and Date objects in response', async () => {
      const regimen = makeFakeRegimen({
        _id: { toString: () => 'reg-obj' },
        createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
        updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
      });
      mockList.mockResolvedValue({
        data: [regimen],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data[0]._id).toBe('reg-obj');
      expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
      expect(body.data[0].updatedAt).toBe('2024-01-02T00:00:00.000Z');
    });

    it('handles actual Date objects for createdAt/updatedAt', async () => {
      const regimen = makeFakeRegimen({
        createdAt: new Date('2024-03-01T00:00:00.000Z'),
        updatedAt: new Date('2024-03-02T00:00:00.000Z'),
      });
      mockList.mockResolvedValue({
        data: [regimen],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data[0].createdAt).toBe('2024-03-01T00:00:00.000Z');
      expect(body.data[0].updatedAt).toBe('2024-03-02T00:00:00.000Z');
    });

    it('includes optional medication fields when present', async () => {
      const regimen = makeFakeRegimen({
        medications: [
          {
            medicineId: 'med-1',
            medicineName: 'Metformin',
            medicineStrength: 500,
            medicineStrengthUnit: StrengthUnit.MG,
            medicineForm: MedicineForm.TABLET,
            dosage: 2,
            dosageUnit: DosageUnit.TABLET,
            frequency: DosageFrequency.CUSTOM,
            customFrequencyPerDay: 4,
            timeOfDay: 'morning',
            instructions: 'Take with food',
          },
        ],
      });
      mockList.mockResolvedValue({
        data: [regimen],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      const med = body.data[0].medications[0];
      expect(med.customFrequencyPerDay).toBe(4);
      expect(med.timeOfDay).toBe('morning');
      expect(med.instructions).toBe('Take with food');
    });

    it('omits null optional medication fields from response', async () => {
      const regimen = makeFakeRegimen();
      mockList.mockResolvedValue({
        data: [regimen],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      const med = body.data[0].medications[0];
      expect(med.customFrequencyPerDay).toBeUndefined();
      expect(med.timeOfDay).toBeUndefined();
      expect(med.instructions).toBeUndefined();
    });

    it('passes query parameters to service', async () => {
      mockList.mockResolvedValue({
        data: [],
        pagination: { cursor: null, hasMore: false },
      });

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/regimens?isActive=true&limit=5',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      expect(mockList).toHaveBeenCalledWith(
        'hh1',
        'kc-1',
        expect.objectContaining({ isActive: true, limit: 5 }),
      );
    });
  });

  describe('GET /api/v1/households/:householdId/regimens/burn-rate', () => {
    it('returns burn rate data array', async () => {
      const burnRateItem = {
        medicineId: 'med-1',
        medicineName: 'Metformin',
        dailyConsumption: 1,
        totalInCabinet: 30,
        daysUntilEmpty: 30,
        earliestExpiry: '2025-01-01T00:00:00.000Z',
        avgUnitPrice: 2.5,
        projectedDailyCost: 2.5,
        projectedMonthlyCost: 75,
        projectedYearlyCost: 912.5,
        currency: 'USD',
      };
      mockCalculateBurnRates.mockResolvedValue([burnRateItem]);

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/regimens/burn-rate',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data).toHaveLength(1);
      expect(body.data[0].medicineId).toBe('med-1');
      expect(body.data[0].medicineName).toBe('Metformin');
      expect(body.data[0].dailyConsumption).toBe(1);
      expect(body.data[0].daysUntilEmpty).toBe(30);
      expect(body.data[0].currency).toBe('USD');
    });

    it('returns empty array when no active regimens', async () => {
      mockCalculateBurnRates.mockResolvedValue([]);

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/regimens/burn-rate',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data).toHaveLength(0);
    });

    it('handles null monetary fields correctly', async () => {
      const burnRateItem = {
        medicineId: 'med-1',
        medicineName: 'Metformin',
        dailyConsumption: 1,
        totalInCabinet: 30,
        daysUntilEmpty: 30,
        earliestExpiry: null,
        avgUnitPrice: null,
        projectedDailyCost: null,
        projectedMonthlyCost: null,
        projectedYearlyCost: null,
        currency: null,
      };
      mockCalculateBurnRates.mockResolvedValue([burnRateItem]);

      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/regimens/burn-rate',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data[0].avgUnitPrice).toBeNull();
      expect(body.data[0].projectedDailyCost).toBeNull();
      expect(body.data[0].projectedMonthlyCost).toBeNull();
      expect(body.data[0].projectedYearlyCost).toBeNull();
      expect(body.data[0].currency).toBeNull();
    });
  });

  describe('GET /api/v1/households/:householdId/regimens/:id', () => {
    it('returns single regimen by id', async () => {
      mockGetById.mockResolvedValue(makeFakeRegimen());

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.name).toBe('Daily Medications');
      expect(body._id).toBe('reg-1');
    });

    it('passes id and householdId to service', async () => {
      mockGetById.mockResolvedValue(makeFakeRegimen());

      await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/regimens/reg-1',
        headers: authHeaders,
      });

      expect(mockGetById).toHaveBeenCalledWith('reg-1', 'hh1', 'kc-1');
    });
  });

  describe('POST /api/v1/households/:householdId/regimens', () => {
    it('creates regimen and returns 201', async () => {
      mockCreate.mockResolvedValue(makeFakeRegimen());

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/regimens',
        headers: authHeaders,
        payload: validPostBody,
      });

      expect(res.statusCode).toBe(201);
      const body = res.json();
      expect(body.name).toBe('Daily Medications');
      expect(body._id).toBe('reg-1');
    });

    it('returns 400 on invalid body with empty medications array', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/regimens',
        headers: authHeaders,
        payload: { name: 'Bad Regimen', isActive: true, medications: [] },
      });

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

    it('returns 400 on invalid body with missing name', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/regimens',
        headers: authHeaders,
        payload: {
          isActive: true,
          medications: [
            {
              medicineId: 'med-1',
              dosage: 1,
              dosageUnit: 'tablet',
              frequency: 'daily',
            },
          ],
        },
      });

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

  describe('PATCH /api/v1/households/:householdId/regimens/:id', () => {
    it('updates regimen and returns 200', async () => {
      mockUpdate.mockResolvedValue(makeFakeRegimen({ name: 'Updated Regimen' }));

      const res = await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/regimens/reg-1',
        headers: authHeaders,
        payload: { name: 'Updated Regimen' },
      });

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

    it('passes id, householdId, and body to service', async () => {
      mockUpdate.mockResolvedValue(makeFakeRegimen({ isActive: false }));

      await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/regimens/reg-1',
        headers: authHeaders,
        payload: { isActive: false },
      });

      expect(mockUpdate).toHaveBeenCalledWith(
        'reg-1',
        'hh1',
        'kc-1',
        expect.objectContaining({ isActive: false }),
      );
    });
  });

  describe('DELETE /api/v1/households/:householdId/regimens/:id', () => {
    it('deletes regimen and returns 204', async () => {
      mockDelete.mockResolvedValue(undefined);

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

      expect(res.statusCode).toBe(204);
      expect(mockDelete).toHaveBeenCalledWith('reg-1', 'hh1', 'kc-1');
    });
  });
});
