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',
      realm_access: { roles: ['member'] },
      householdIds: ['hh1'],
    },
    protectedHeader: {},
    key: {},
  }),
}));

const mockCreate = vi.fn();
const mockCreateMany = vi.fn();
const mockFindByProduct = vi.fn();
const mockCompareStores = vi.fn();
const mockGetAnalytics = vi.fn();

vi.mock('../../../src/modules/prices/prices.repository.js', () => ({
  PricesRepository: class {
    create = mockCreate;
    createMany = mockCreateMany;
    findByProduct = mockFindByProduct;
    compareStores = mockCompareStores;
    getAnalytics = mockGetAnalytics;
  },
}));

vi.mock('../../../src/modules/products/products.repository.js', () => ({
  ProductsRepository: class {
    findById = vi.fn().mockResolvedValue({ name: 'Mock Product' });
    findByIds = vi.fn().mockResolvedValue([{ _id: 'p1', name: 'Mock Product' }]);
  },
}));

vi.mock('../../../src/modules/stores/stores.repository.js', () => ({
  StoresRepository: class {
    findById = vi.fn().mockResolvedValue({ name: 'Mock Store' });
  },
}));

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

describe('prices.routes', () => {
  let app: any;

  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(pricesRoutes);
    await instance.ready();
    return instance;
  }

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

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

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

  function makeRecord(overrides = {}) {
    return {
      _id: 'r1',
      householdId: 'hh1',
      productId: 'p1',
      productName: 'Apples',
      storeId: 's1',
      storeName: 'Store',
      price: 10,
      currency: 'USD',
      quantity: 1,
      unit: 'piece',
      pricePerUnit: 10,
      date: new Date(),
      createdBy: 'kc-1',
      createdAt: new Date(),
      ...overrides,
    };
  }

  describe('POST /api/v1/households/:householdId/prices', () => {
    it('records price and returns 201 response', async () => {
      mockCreate.mockResolvedValue(
        makeRecord({
          receiptImageUrl: 'http://test.com/img.jpg',
          notes: 'Custom notes',
          date: '2026-05-14T00:00:00.000Z',
        })
      );

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/prices',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        body: JSON.stringify({
          productId: 'p1',
          storeId: 's1',
          price: 5.99,
          currency: 'USD',
          quantity: 1,
          unit: 'piece',
        }),
      });

      if (res.statusCode === 500) {
        console.log('ERROR PAYLOAD:', res.payload);
      }
      expect(res.statusCode).toBe(201);
      expect(res.json().productName).toBe('Apples');
    });
  });

  describe('GET /api/v1/households/:householdId/prices/history/:productId', () => {
    it('returns a paginated envelope of historical pricing data', async () => {
      mockFindByProduct.mockResolvedValue({
        data: [makeRecord()],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data).toHaveLength(1);
      expect(body.pagination.hasMore).toBe(false);
    });
  });

  describe('GET /api/v1/households/:householdId/prices/analytics', () => {
    it('returns analytical metrics suite with properly formatted dates', async () => {
      mockGetAnalytics.mockResolvedValue({
        spendingOverTime: [],
        averageBasketByStore: [],
        spendingByCategory: [],
        priceAlerts: [{ productId: 'p1', productName: 'Bread', storeId: 's1', storeName: 'Store', previousPrice: 2, currentPrice: 2.5, changePercent: 25, date: new Date() }],
      });

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

      if (res.statusCode === 500) {
        console.log('ERROR PAYLOAD:', res.payload);
      }
      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.priceAlerts).toHaveLength(1);
      expect(typeof body.priceAlerts[0].date).toBe('string');
    });
  });

  describe('POST /api/v1/households/:householdId/prices/bulk', () => {
    it('records bulk prices and returns 201', async () => {
      mockCreateMany.mockResolvedValue([makeRecord()]);
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/prices/bulk',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        body: JSON.stringify({
          storeId: 's1',
          items: [{ productId: 'p1', price: 10, quantity: 1, unit: 'piece' }],
        }),
      });
      expect(res.statusCode).toBe(201);
      expect(res.json()[0].productName).toBe('Apples');
    });
  });

  describe('GET /api/v1/households/:householdId/prices/compare/:productId', () => {
    it('returns comparison array', async () => {
      mockCompareStores.mockResolvedValue([{ storeId: 's1', storeName: 'Store', latestPrice: 10, latestPricePerUnit: 10, currency: 'USD', date: new Date() }]);
      const res = await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/prices/compare/p1',
        headers: authHeaders,
      });
      expect(res.statusCode).toBe(200);
      expect(res.json().data).toHaveLength(1);
    });
  });
});
