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

vi.mock('../../../src/modules/stores/stores.repository.js', () => ({
  StoresRepository: class {
    findByHousehold = vi.fn();
    findById = vi.fn();
    create = vi.fn();
    update = vi.fn();
    deactivate = vi.fn();
  },
}));

vi.mock('../../../src/modules/stores/stores.service.js', () => ({
  StoresService: class {
    list = mockList;
    getById = mockGetById;
    create = mockCreate;
    update = mockUpdate;
    deactivate = mockDeactivate;
  },
}));

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

function makeFakeStore(overrides = {}) {
  return {
    _id: 'st-1',
    householdId: 'hh1',
    name: 'Walgreens',
    tags: ['pharmacy'],
    isActive: true,
    createdBy: 'kc-1',
    createdAt: '2024-06-01T00:00:00.000Z',
    updatedAt: '2024-06-01T00:00:00.000Z',
    ...overrides,
  };
}

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

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data).toHaveLength(1);
      expect(body.data[0].name).toBe('Walgreens');
      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/stores?tags=pharmacy&search=cvs&limit=5',
        headers: authHeaders,
      });

      expect(mockList).toHaveBeenCalledWith(
        'hh1',
        expect.objectContaining({ tags: 'pharmacy', search: 'cvs', limit: 5 }),
      );
    });

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

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

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

    it('includes optional fields in response when present', async () => {
      mockList.mockResolvedValue({
        data: [
          makeFakeStore({
            address: '123 Main St',
            location: { lat: 40.7128, lng: -74.006 },
            url: 'https://walgreens.com',
            notes: 'Open 24h',
          }),
        ],
        pagination: { cursor: null, hasMore: false },
      });

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

      expect(res.statusCode).toBe(200);
      const body = res.json();
      expect(body.data[0].address).toBe('123 Main St');
      expect(body.data[0].location).toEqual({ lat: 40.7128, lng: -74.006 });
      expect(body.data[0].url).toBe('https://walgreens.com');
      expect(body.data[0].notes).toBe('Open 24h');
    });
  });

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

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

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

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

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

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

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

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

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

    it('passes userId to service', async () => {
      mockCreate.mockResolvedValue(makeFakeStore());

      await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/stores',
        headers: authHeaders,
        payload: { name: 'CVS' },
      });

      expect(mockCreate).toHaveBeenCalledWith(
        expect.objectContaining({ name: 'CVS' }),
        'hh1',
        'kc-1',
      );
    });

    it('returns 400 for missing name', async () => {
      const res = await app.inject({
        method: 'POST',
        url: '/api/v1/households/hh1/stores',
        headers: authHeaders,
        payload: {},
      });

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

  describe('PATCH /api/v1/households/:householdId/stores/:id', () => {
    it('updates store and returns 200', async () => {
      mockUpdate.mockResolvedValue(makeFakeStore({ name: 'CVS' }));

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

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

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

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

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

  describe('DELETE /api/v1/households/:householdId/stores/:id', () => {
    it('deactivates store and returns 200', async () => {
      mockDeactivate.mockResolvedValue(makeFakeStore({ isActive: false }));

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

      expect(res.statusCode).toBe(200);
      expect(res.json().isActive).toBe(false);
    });

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

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

      expect(mockDeactivate).toHaveBeenCalledWith('st-1', 'hh1');
    });
  });
});
