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 { ProductCategory, ServingUnit, ProductSource } 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 {
  mockFindByHousehold,
  mockFindById,
  mockFindByBarcode,
  mockFindDuplicate,
  mockCreate,
  mockUpdate,
  mockSoftDelete,
  mockBulkCreate,
  mockBarcodeLookup,
} = vi.hoisted(() => ({
  mockFindByHousehold: vi.fn(),
  mockFindById: vi.fn(),
  mockFindByBarcode: vi.fn(),
  mockFindDuplicate: vi.fn(),
  mockCreate: vi.fn(),
  mockUpdate: vi.fn(),
  mockSoftDelete: vi.fn(),
  mockBulkCreate: vi.fn(),
  mockBarcodeLookup: vi.fn(),
}));

vi.mock('../../../src/modules/products/products.repository.js', () => ({
  ProductsRepository: class {
    findByHousehold = mockFindByHousehold;
    findById = mockFindById;
    findByIds = vi.fn();
    findByBarcode = mockFindByBarcode;
    findDuplicate = mockFindDuplicate;
    create = mockCreate;
    update = mockUpdate;
    softDelete = mockSoftDelete;
    bulkCreate = mockBulkCreate;
  },
}));

vi.mock('../../../src/modules/products/barcode.service.js', () => ({
  BarcodeService: class {
    lookup = mockBarcodeLookup;
  },
}));

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

function makeFakeProduct(overrides: Record<string, unknown> = {}) {
  return {
    _id: 'p1',
    householdId: 'hh1',
    name: 'Chicken Breast',
    category: ProductCategory.MEAT,
    servingSize: 100,
    servingUnit: ServingUnit.GRAMS,
    nutrition: { calories: 165, protein: 31, carbs: 0, fat: 3.6 },
    tags: [],
    source: ProductSource.MANUAL,
    createdBy: 'kc-1',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    ...overrides,
  };
}

describe('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(productsRoutes);
    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/products', () => {
    it('returns paginated list', async () => {
      const product = makeFakeProduct();
      mockFindByHousehold.mockResolvedValue({
        data: [product],
        pagination: { cursor: null, hasMore: false },
      });

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

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

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

      await app.inject({
        method: 'GET',
        url: '/api/v1/households/hh1/products?q=chicken&category=meat&limit=10',
        headers: authHeaders,
      });

      expect(mockFindByHousehold).toHaveBeenCalledWith(
        'hh1',
        expect.objectContaining({ q: 'chicken', category: ProductCategory.MEAT, limit: 10 }),
      );
    });

    it('handles ObjectId and Date objects in response', async () => {
      const product = makeFakeProduct({
        _id: { toString: () => 'pid-obj' },
        createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
        updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
        brand: 'Tyson',
        densityGPerMl: 1.05,
      });
      mockFindByHousehold.mockResolvedValue({
        data: [product],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data[0]._id).toBe('pid-obj');
      expect(body.data[0].brand).toBe('Tyson');
      expect(body.data[0].densityGPerMl).toBe(1.05);
    });
  });

  describe('GET /api/v1/households/:householdId/products/barcode/:code', () => {
    it('returns product when found by barcode', async () => {
      mockBarcodeLookup.mockResolvedValue({
        found: true,
        product: makeFakeProduct({ barcode: '1234567890' }),
        cached: true,
      });

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

      expect(res.statusCode).toBe(200);
      expect(res.json().name).toBe('Chicken Breast');
    });

    it('returns 404 when barcode not found', async () => {
      mockBarcodeLookup.mockResolvedValue({ found: false });

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

      expect(res.statusCode).toBe(404);
      expect(res.json().found).toBe(false);
    });
  });

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

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

      expect(res.statusCode).toBe(200);
      expect(res.json().name).toBe('Chicken Breast');
    });

    it('returns 404 when product not found', async () => {
      mockFindById.mockResolvedValue(null);

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

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

  describe('POST /api/v1/households/:householdId/products', () => {
    it('creates a product and returns 201', async () => {
      mockFindByBarcode.mockResolvedValue(null);
      mockFindDuplicate.mockResolvedValue(null);
      mockCreate.mockResolvedValue(makeFakeProduct());

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        payload: {
          name: 'Chicken Breast',
          category: ProductCategory.MEAT,
          servingSize: 100,
          servingUnit: ServingUnit.GRAMS,
          nutrition: { calories: 165, protein: 31, carbs: 0, fat: 3.6 },
        },
      });

      expect(res.statusCode).toBe(201);
      expect(res.json().name).toBe('Chicken Breast');
    });

    it('returns 409 on barcode conflict', async () => {
      mockFindByBarcode.mockResolvedValue(makeFakeProduct());

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        payload: {
          name: 'Chicken Breast',
          category: ProductCategory.MEAT,
          servingSize: 100,
          servingUnit: ServingUnit.GRAMS,
          nutrition: { calories: 165, protein: 31, carbs: 0, fat: 3.6 },
          barcode: '1234567890',
        },
      });

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

    it('returns 400 on validation failure', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        payload: { name: '' }, // missing required fields
      });

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

  describe('PATCH /api/v1/households/:householdId/products/:id', () => {
    it('updates product', async () => {
      const product = makeFakeProduct();
      mockFindById.mockResolvedValue(product);
      mockFindByBarcode.mockResolvedValue(null);
      mockFindDuplicate.mockResolvedValue(null);
      mockUpdate.mockResolvedValue({ ...product, name: 'Updated' });

      const res = await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/products/p1',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        payload: { name: 'Updated' },
      });

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

    it('returns 404 for unknown product', async () => {
      mockFindById.mockResolvedValue(null);

      const res = await app.inject({
        method: 'PATCH',
        url: '/api/v1/households/hh1/products/missing',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        payload: { name: 'X' },
      });

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

  describe('DELETE /api/v1/households/:householdId/products/:id', () => {
    it('returns 204 on successful delete', async () => {
      const product = makeFakeProduct();
      mockFindById.mockResolvedValue(product);
      mockSoftDelete.mockResolvedValue({ ...product, deletedAt: new Date() });

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

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

    it('returns 404 for unknown product', async () => {
      mockFindById.mockResolvedValue(null);

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

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

  describe('POST /api/v1/households/:householdId/products/smart-add', () => {
    it('returns available:false with NoOp provider', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/smart-add',
        headers: { ...authHeaders, 'content-type': 'application/json' },
        payload: { text: 'chicken breast 100g' },
      });

      expect(res.statusCode).toBe(200);
      expect(res.json()).toEqual({ available: false, message: 'LLM not configured' });
    });
  });

  describe('POST /api/v1/households/:householdId/products/import', () => {
    it('imports products from CSV file', async () => {
      mockFindByBarcode.mockResolvedValue(null);
      mockFindDuplicate.mockResolvedValue(null);
      mockBulkCreate.mockResolvedValue([]);

      const csv =
        'name,category,servingSize,servingUnit,calories,protein,carbs,fat\nRice,grains,100,g,130,2.7,28,0.3';
      const boundary = '----FormBoundary';
      const body = [
        `--${boundary}`,
        'Content-Disposition: form-data; name="file"; filename="products.csv"',
        'Content-Type: text/csv',
        '',
        csv,
        `--${boundary}--`,
      ].join('\r\n');

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/import',
        headers: { ...authHeaders, 'content-type': `multipart/form-data; boundary=${boundary}` },
        payload: body,
      });

      expect(res.statusCode).toBe(200);
      const json = res.json();
      expect(json.imported).toBe(1);
      expect(json.skipped).toBe(0);
      expect(json.errors).toHaveLength(0);
    });

    it('imports products from JSON file', async () => {
      mockFindByBarcode.mockResolvedValue(null);
      mockFindDuplicate.mockResolvedValue(null);
      mockBulkCreate.mockResolvedValue([]);

      const jsonData = JSON.stringify([
        {
          name: 'Beans',
          category: 'legumes',
          servingSize: 100,
          servingUnit: 'g',
          nutrition: { calories: 120, protein: 8, carbs: 20, fat: 0.5 },
          tags: [],
        },
      ]);
      const boundary = '----FormBoundary';
      const body = [
        `--${boundary}`,
        'Content-Disposition: form-data; name="file"; filename="products.json"',
        'Content-Type: application/json',
        '',
        jsonData,
        `--${boundary}--`,
      ].join('\r\n');

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/import',
        headers: { ...authHeaders, 'content-type': `multipart/form-data; boundary=${boundary}` },
        payload: body,
      });

      expect(res.statusCode).toBe(200);
      expect(res.json().imported).toBe(1);
    });

    it('returns 400 when no file uploaded', async () => {
      const boundary = '----FormBoundary';
      const body = `--${boundary}--`;

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/import',
        headers: { ...authHeaders, 'content-type': `multipart/form-data; boundary=${boundary}` },
        payload: body,
      });

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

    it('returns 400 for invalid JSON', async () => {
      const boundary = '----FormBoundary';
      const body = [
        `--${boundary}`,
        'Content-Disposition: form-data; name="file"; filename="bad.json"',
        'Content-Type: application/json',
        '',
        '{not valid json',
        `--${boundary}--`,
      ].join('\r\n');

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/import',
        headers: { ...authHeaders, 'content-type': `multipart/form-data; boundary=${boundary}` },
        payload: body,
      });

      expect(res.statusCode).toBe(400);
      expect(res.json().error).toBe('Invalid JSON');
    });

    it('returns 400 when JSON is not an array', async () => {
      const boundary = '----FormBoundary';
      const body = [
        `--${boundary}`,
        'Content-Disposition: form-data; name="file"; filename="obj.json"',
        'Content-Type: application/json',
        '',
        '{"name": "not an array"}',
        `--${boundary}--`,
      ].join('\r\n');

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/import',
        headers: { ...authHeaders, 'content-type': `multipart/form-data; boundary=${boundary}` },
        payload: body,
      });

      expect(res.statusCode).toBe(400);
      expect(res.json().error).toBe('JSON must be an array');
    });

    it('returns 400 when JSON exceeds max rows', async () => {
      const items = Array.from({ length: 5001 }, (_, i) => ({
        name: `Item ${i}`,
        category: 'other',
        servingSize: 100,
        servingUnit: 'g',
        nutrition: { calories: 0, protein: 0, carbs: 0, fat: 0 },
        tags: [],
      }));
      const boundary = '----FormBoundary';
      const body = [
        `--${boundary}`,
        'Content-Disposition: form-data; name="file"; filename="big.json"',
        'Content-Type: application/json',
        '',
        JSON.stringify(items),
        `--${boundary}--`,
      ].join('\r\n');

      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/products/import',
        headers: { ...authHeaders, 'content-type': `multipart/form-data; boundary=${boundary}` },
        payload: body,
      });

      expect(res.statusCode).toBe(400);
      expect(res.json().error).toContain('5000');
    });
  });

  describe('toProductResponse optional fields', () => {
    it('includes optional nutrition fields and imageUrl when present', async () => {
      mockFindByHousehold.mockResolvedValue({
        data: [
          makeFakeProduct({
            densityGPerMl: 1.1,
            imageUrl: 'https://example.com/img.jpg',
            deletedAt: new Date().toISOString(),
            nutrition: {
              calories: 100,
              protein: 5,
              carbs: 10,
              fat: 2,
              fiber: 3,
              sugar: 1,
              sodium: 50,
              saturatedFat: 0.5,
              cholesterol: 10,
            },
          }),
        ],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const product = res.json().data[0];
      expect(product.densityGPerMl).toBe(1.1);
      expect(product.imageUrl).toBe('https://example.com/img.jpg');
      expect(product.deletedAt).toBeDefined();
      expect(product.nutrition.fiber).toBe(3);
      expect(product.nutrition.sugar).toBe(1);
      expect(product.nutrition.sodium).toBe(50);
      expect(product.nutrition.saturatedFat).toBe(0.5);
      expect(product.nutrition.cholesterol).toBe(10);
    });
  });
});
