import { Test, type TestingModule } from '@nestjs/testing';
import { NotFoundException } from '@nestjs/common';
import { TransportServiceService } from './transport-service.service';
import { TransportServiceRepository } from './repositories/transport-service.repository';

describe('TransportServiceService', () => {
  let service: TransportServiceService;

  const mockRepo = {
    findAllWithDestination: jest.fn(),
    findPaginated: jest.fn(),
    findByIdWithDestination: jest.fn(),
    findByShortCode: jest.fn(),
    findById: jest.fn(),
    save: jest.fn(),
    update: jest.fn(),
    softDelete: jest.fn(),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        TransportServiceService,
        { provide: TransportServiceRepository, useValue: mockRepo },
      ],
    }).compile();

    service = module.get<TransportServiceService>(TransportServiceService);
  });

  afterEach(() => jest.clearAllMocks());

  describe('findAll', () => {
    it('should return paginated transport services with destinations', async () => {
      const items = [{ id: '1', short_code: 'TS-001' }];
      const paginated = {
        items,
        meta: { total: 1, page: 1, limit: 10, totalPages: 1 },
      };
      mockRepo.findPaginated.mockResolvedValue(paginated);

      const result = await service.findAll();

      expect(result).toEqual(paginated);
      expect(mockRepo.findPaginated).toHaveBeenCalledTimes(1);
    });

    it('should return empty paginated result when no transport services exist', async () => {
      const paginated = {
        items: [],
        meta: { total: 0, page: 1, limit: 10, totalPages: 0 },
      };
      mockRepo.findPaginated.mockResolvedValue(paginated);
      const result = await service.findAll();
      expect(result).toEqual(paginated);
    });
  });

  describe('findById', () => {
    it('should return the transport service when found', async () => {
      const item = { id: '1', short_code: 'TS-001' };
      mockRepo.findByIdWithDestination.mockResolvedValue(item);

      const result = await service.findById('1');

      expect(result).toEqual(item);
      expect(mockRepo.findByIdWithDestination).toHaveBeenCalledWith('1');
    });

    it('should throw NotFoundException when transport service not found', async () => {
      mockRepo.findByIdWithDestination.mockResolvedValue(null);

      await expect(service.findById('999')).rejects.toThrow(NotFoundException);
    });
  });

  describe('create', () => {
    const createDto = {
      short_code: 'TS-001',
      destination_id: 'dest-1',
      category: 'transfer',
      from_city: 'City A',
      to_city: 'City B',
    };

    it('should create and return success response', async () => {
      mockRepo.findByShortCode.mockResolvedValue(null);
      mockRepo.save.mockResolvedValue({ id: 'new-1' });

      const result = await service.create(createDto);

      expect(result).toEqual({ id: 'new-1', message: 'Transport service created successfully' });
      expect(mockRepo.save).toHaveBeenCalledTimes(1);
    });

    // short_code is auto-derived from from_city + to_city + category.
    // When the explicit DTO value is dropped, the helper resolves
    // collisions by suffixing — never throws. Assert the auto-derive
    // path produces a valid code.
    it('auto-derives short_code from route + category when DTO omits it', async () => {
      mockRepo.findByShortCode.mockResolvedValueOnce({ id: 'existing' });
      mockRepo.findByShortCode.mockResolvedValueOnce(null);
      mockRepo.save.mockImplementation(async (payload: any) => ({ id: 'new-1', ...payload }));

      await service.create({ ...createDto, short_code: undefined } as any);

      const saved = mockRepo.save.mock.calls[0][0];
      // First 12 alphanumeric upper of "City A" + "City B" + "transfer"
      // = "CITYACITYBTR"; "CITYACITYBTR" taken → suffix 1
      expect(saved.short_code).toBe('CITYACITYBTR1');
    });
  });

  describe('update', () => {
    const existingItem = { id: '1', short_code: 'TS-001' };

    it('should update and return success response', async () => {
      mockRepo.findById.mockResolvedValue(existingItem);
      mockRepo.update.mockResolvedValue(undefined);

      const result = await service.update('1', { from_city: 'New City' });

      expect(result).toEqual({ id: '1', message: 'Transport service updated successfully' });
    });

    it('should throw NotFoundException when transport service not found', async () => {
      mockRepo.findById.mockResolvedValue(null);

      await expect(service.update('999', {} as any)).rejects.toThrow(NotFoundException);
    });

    // short_code is immutable post-create; the update path silently
    // strips it from the payload regardless of value.
    it('ignores short_code in update payload (immutable post-create)', async () => {
      mockRepo.findById.mockResolvedValue(existingItem);
      mockRepo.update.mockResolvedValue(undefined);

      await service.update('1', { short_code: 'TS-002' } as any);

      const updateArg = mockRepo.update.mock.calls[0][1];
      expect(updateArg).not.toHaveProperty('short_code');
      expect(mockRepo.findByShortCode).not.toHaveBeenCalled();
    });
  });

  describe('remove', () => {
    it('should soft delete and return success message', async () => {
      mockRepo.findById.mockResolvedValue({ id: '1' });
      mockRepo.softDelete.mockResolvedValue(undefined);

      const result = await service.remove('1');

      expect(result).toEqual({ message: 'Transport service deleted successfully' });
      expect(mockRepo.softDelete).toHaveBeenCalledWith('1');
    });

    it('should throw NotFoundException when transport service not found', async () => {
      mockRepo.findById.mockResolvedValue(null);

      await expect(service.remove('999')).rejects.toThrow(NotFoundException);
    });
  });
});
