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';

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

vi.mock('../../../src/modules/purchases/purchases.repository.js', () => ({
  PurchasesRepository: class {
    create = vi.fn();
    findByHousehold = vi.fn();
    findById = vi.fn();
    update = vi.fn();
    receiveAll = vi.fn();
    softDelete = vi.fn();
    getPendingMedicineStock = vi.fn();
  },
}));

vi.mock('../../../src/modules/purchases/purchases.service.js', () => ({
  PurchasesService: class {
    list = mockList;
    getById = mockGetById;
    create = mockCreate;
    update = mockUpdate;
    receive = mockReceive;
    delete = mockDelete;
  },
}));

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

function makeFakePurchase(overrides = {}) {
  return {
    _id: 'p-1',
    householdId: 'hh1',
    storeId: 'st-1',
    storeName: 'CVS',
    status: 'in_cabinet',
    items: [
      {
        _id: 'item-1',
        medicineProductId: 'mp-1',
        medicineId: 'med-1',
        name: 'Advil',
        quantity: 30,
        unit: 'tablet',
        addedToCabinet: true,
      },
    ],
    purchasedAt: '2026-01-15T00:00:00.000Z',
    createdBy: 'kc-1',
    createdAt: '2026-01-15T00:00:00.000Z',
    updatedAt: '2026-01-15T00:00:00.000Z',
    ...overrides,
  };
}

describe('purchases.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(purchasesRoutes);
    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/purchases', () => {
    it('returns paginated purchase list', async () => {
      mockList.mockResolvedValue({
        data: [makeFakePurchase()],
        pagination: { cursor: null, hasMore: false },
      });

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

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

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

      await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/purchases?status=ordered&limit=10',
        headers: authHeaders,
      });

      expect(mockList).toHaveBeenCalledWith(
        'hh1',
        expect.objectContaining({ status: 'ordered', limit: 10 }),
      );
    });

    it('serializes ObjectId _id to string', async () => {
      mockList.mockResolvedValue({
        data: [makeFakePurchase({ _id: { toString: () => 'p-obj' } })],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      expect(res.json().data[0]._id).toBe('p-obj');
    });

    it('converts Date objects to ISO strings', async () => {
      mockList.mockResolvedValue({
        data: [
          makeFakePurchase({
            purchasedAt: new Date('2026-01-15T00:00:00.000Z'),
            createdAt: new Date('2026-01-15T00:00:00.000Z'),
            updatedAt: new Date('2026-01-15T00:00:00.000Z'),
          }),
        ],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const item = res.json().data[0];
      expect(item.purchasedAt).toBe('2026-01-15T00:00:00.000Z');
      expect(item.createdAt).toBe('2026-01-15T00:00:00.000Z');
    });

    it('includes optional fields in item response when present', async () => {
      mockList.mockResolvedValue({
        data: [
          makeFakePurchase({
            notes: 'picked up on the way home',
            items: [
              {
                _id: 'item-1',
                medicineProductId: 'mp-1',
                medicineId: 'med-1',
                name: 'Advil',
                quantity: 30,
                unit: 'tablet',
                actualPrice: 9.99,
                currency: 'USD',
                addedToCabinet: true,
              },
            ],
          }),
        ],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const item = res.json().data[0].items[0];
      expect(item.actualPrice).toBe(9.99);
      expect(item.currency).toBe('USD');
      expect(res.json().data[0].notes).toBe('picked up on the way home');
    });

    it('handles item with ObjectId _id and priceRecordId', async () => {
      mockList.mockResolvedValue({
        data: [
          makeFakePurchase({
            items: [
              {
                _id: { toString: () => 'item-obj' },
                name: 'Advil',
                quantity: 10,
                unit: 'tablet',
                priceRecordId: 'pr-1',
                addedToCabinet: false,
              },
            ],
          }),
        ],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const item = res.json().data[0].items[0];
      expect(item._id).toBe('item-obj');
      expect(item.priceRecordId).toBe('pr-1');
    });

    it('handles item without _id and includes receivedAt on purchase', async () => {
      mockList.mockResolvedValue({
        data: [
          makeFakePurchase({
            status: 'in_cabinet',
            receivedAt: '2026-01-20T00:00:00.000Z',
            items: [
              {
                name: 'Generic',
                quantity: 5,
                unit: 'tablet',
                addedToCabinet: true,
              },
            ],
          }),
        ],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const purchase = res.json().data[0];
      expect(purchase.items[0]._id).toBe('');
      expect(purchase.receivedAt).toBe('2026-01-20T00:00:00.000Z');
    });
  });

  describe('GET /api/v1/households/:householdId/purchases/:id', () => {
    it('returns single purchase', async () => {
      mockGetById.mockResolvedValue(makeFakePurchase());

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

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

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

      await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/purchases/p-99',
        headers: authHeaders,
      });

      expect(mockGetById).toHaveBeenCalledWith('p-99', 'hh1');
    });
  });

  describe('POST /api/v1/households/:householdId/purchases', () => {
    const validBody = {
      storeId: 'st-1',
      items: [{ name: 'Advil', quantity: 30, unit: 'tablet' }],
    };

    it('creates purchase and returns 201', async () => {
      mockCreate.mockResolvedValue(makeFakePurchase());

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

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

    it('passes body, householdId, and userId to service', async () => {
      mockCreate.mockResolvedValue(makeFakePurchase());

      await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/purchases',
        headers: authHeaders,
        payload: { ...validBody, status: 'ordered' },
      });

      expect(mockCreate).toHaveBeenCalledWith(
        expect.objectContaining({ storeId: 'st-1', status: 'ordered' }),
        'hh1',
        'kc-1',
      );
    });

    it('returns 400 for missing storeId', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/purchases',
        headers: authHeaders,
        payload: { items: [{ name: 'X', quantity: 1, unit: 'tablet' }] },
      });

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

    it('returns 400 for empty items array', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/purchases',
        headers: authHeaders,
        payload: { storeId: 'st-1', items: [] },
      });

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

  describe('PATCH /api/v1/households/:householdId/purchases/:id', () => {
    it('updates purchase and returns 200', async () => {
      mockUpdate.mockResolvedValue(makeFakePurchase({ notes: 'updated note' }));

      const res = await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/purchases/p-1',
        headers: authHeaders,
        payload: { notes: 'updated note' },
      });

      expect(res.statusCode).toBe(200);
      expect(res.json().notes).toBe('updated note');
    });

    it('passes id, householdId, and body to service', async () => {
      mockUpdate.mockResolvedValue(makeFakePurchase());

      await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/purchases/p-1',
        headers: authHeaders,
        payload: { notes: 'note' },
      });

      expect(mockUpdate).toHaveBeenCalledWith(
        'p-1',
        'hh1',
        expect.objectContaining({ notes: 'note' }),
      );
    });
  });

  describe('POST /api/v1/households/:householdId/purchases/:id/receive', () => {
    it('returns addedCount and priceRecordsCreated', async () => {
      mockReceive.mockResolvedValue({ addedCount: 2, priceRecordsCreated: 1 });

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/purchases/p-1/receive',
        headers: authHeaders,
      });

      expect(res.statusCode).toBe(200);
      expect(res.json()).toEqual({ addedCount: 2, priceRecordsCreated: 1 });
    });

    it('passes id, householdId, and userId to service', async () => {
      mockReceive.mockResolvedValue({ addedCount: 0, priceRecordsCreated: 0 });

      await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/purchases/p-1/receive',
        headers: authHeaders,
      });

      expect(mockReceive).toHaveBeenCalledWith('p-1', 'hh1', 'kc-1');
    });
  });

  describe('DELETE /api/v1/households/:householdId/purchases/:id', () => {
    it('deletes purchase and returns 200', async () => {
      mockDelete.mockResolvedValue(makeFakePurchase());

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

      expect(res.statusCode).toBe(200);
      expect(res.json()._id).toBe('p-1');
    });

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

      await app.inject({
        method: 'DELETE',
        url: '/api/v1/households/hh1/purchases/p-1',
        headers: authHeaders,
      });

      expect(mockDelete).toHaveBeenCalledWith('p-1', 'hh1');
    });
  });
});
