// src/routes/personalization.routes.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import supertest from 'supertest';
import personalizationRouter from './personalization.routes';
import { createMockMasterGroceryItem, createMockDietaryRestriction, createMockAppliance } from '../tests/utils/mockFactories';
import { mockLogger } from '../tests/utils/mockLogger';
import { createTestApp } from '../tests/utils/createTestApp';

// 1. Mock the Service Layer directly.
vi.mock('../services/db/index.db', () => ({
  personalizationRepo: {
    getAllMasterItems: vi.fn(),
    getDietaryRestrictions: vi.fn(),
    getAppliances: vi.fn(),
  },
}));

// Mock the logger to keep test output clean
vi.mock('../services/logger.server', () => ({
  logger: mockLogger,
}));

// Import the mocked db module to control its functions in tests
import * as db from '../services/db/index.db';

describe('Personalization Routes (/api/personalization)', () => {
  const app = createTestApp({ router: personalizationRouter, basePath: '/api/personalization' });

  // Add a basic error handler to capture errors passed to next(err) and return JSON.
  // This prevents unhandled error crashes in tests and ensures we get the 500 response we expect.
  app.use((err: any, req: any, res: any, next: any) => {
    res.status(err.status || 500).json({ message: err.message, errors: err.errors });
  });

  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('GET /master-items', () => {
    it('should return a list of master items', async () => {
      const mockItems = [createMockMasterGroceryItem({ master_grocery_item_id: 1, name: 'Milk' })];
      vi.mocked(db.personalizationRepo.getAllMasterItems).mockResolvedValue(mockItems);

      const response = await supertest(app).get('/api/personalization/master-items');

      expect(response.status).toBe(200);
      expect(response.body).toEqual(mockItems);
    });

    it('should return 500 if the database call fails', async () => {
      vi.mocked(db.personalizationRepo.getAllMasterItems).mockRejectedValue(new Error('DB Error'));
      const response = await supertest(app).get('/api/personalization/master-items');
      expect(response.status).toBe(500);
      expect(response.body.message).toBe('DB Error');
    });

    it('should return 500 if the database call fails for dietary restrictions', async () => {
      vi.mocked(db.personalizationRepo.getDietaryRestrictions).mockRejectedValue(new Error('DB Error'));
      const response = await supertest(app).get('/api/personalization/dietary-restrictions');
      expect(response.status).toBe(500);
      expect(response.body.message).toBe('DB Error');
    });
  });

  describe('GET /dietary-restrictions', () => {
    it('should return a list of all dietary restrictions', async () => {
      const mockRestrictions = [createMockDietaryRestriction({ name: 'Gluten-Free' })];
      vi.mocked(db.personalizationRepo.getDietaryRestrictions).mockResolvedValue(mockRestrictions);

      const response = await supertest(app).get('/api/personalization/dietary-restrictions');

      expect(response.status).toBe(200);
      expect(response.body).toEqual(mockRestrictions);
    });

    it('should return 500 if the database call fails', async () => {
      vi.mocked(db.personalizationRepo.getDietaryRestrictions).mockRejectedValue(new Error('DB Error'));
      const response = await supertest(app).get('/api/personalization/dietary-restrictions');
      expect(response.status).toBe(500);
      expect(response.body.message).toBe('DB Error');
    });
  });

  describe('GET /appliances', () => {
    it('should return a list of all appliances', async () => {
      const mockAppliances = [createMockAppliance({ name: 'Air Fryer' })];
      vi.mocked(db.personalizationRepo.getAppliances).mockResolvedValue(mockAppliances);

      const response = await supertest(app).get('/api/personalization/appliances');

      expect(response.status).toBe(200);
      expect(response.body).toEqual(mockAppliances);
    });

    it('should return 500 if the database call fails', async () => {
      vi.mocked(db.personalizationRepo.getAppliances).mockRejectedValue(new Error('DB Error'));
      const response = await supertest(app).get('/api/personalization/appliances');
      expect(response.status).toBe(500);
      expect(response.body.message).toBe('DB Error');
    });
  });
});