import { Test, TestingModule } from '@nestjs/testing';
import { ConflictException, NotFoundException } from '@nestjs/common';
import { TripSourceService } from './trip-source.service';
import { TripSourceRepository } from './repositories/trip-source.repository';

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

  const mockRepo = {
    findAllSorted: jest.fn(),
    findById: jest.fn(),
    findByShortName: jest.fn(),
    save: jest.fn(),
    update: jest.fn(),
    softDelete: jest.fn(),
  };

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

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

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

  describe('findAll', () => {
    it('should return all trip sources sorted', async () => {
      const items = [{ id: '1', name: 'Agency A' }];
      mockRepo.findAllSorted.mockResolvedValue(items);

      const result = await service.findAll();

      expect(result).toEqual(items);
      expect(mockRepo.findAllSorted).toHaveBeenCalledTimes(1);
    });

    it('should return empty array when no trip sources exist', async () => {
      mockRepo.findAllSorted.mockResolvedValue([]);
      const result = await service.findAll();
      expect(result).toEqual([]);
    });
  });

  describe('findById', () => {
    it('should return the trip source when found', async () => {
      const item = { id: '1', name: 'Agency A' };
      mockRepo.findById.mockResolvedValue(item);

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

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

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

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

  describe('create', () => {
    const createDto = {
      source_type: 'agent',
      name: 'Agency A',
      short_name: 'AA',
      contact_name: 'John',
    };

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

      const result = await service.create(createDto as any);

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

    it('should throw ConflictException when short_name already exists', async () => {
      mockRepo.findByShortName.mockResolvedValue({ id: 'existing' });

      await expect(service.create(createDto as any)).rejects.toThrow(ConflictException);
      expect(mockRepo.save).not.toHaveBeenCalled();
    });
  });

  describe('update', () => {
    const existingItem = { id: '1', short_name: 'AA' };

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

      const result = await service.update('1', { name: 'Updated Agency' } as any);

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

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

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

    it('should throw ConflictException when short_name conflicts with another source', async () => {
      mockRepo.findById.mockResolvedValue(existingItem);
      mockRepo.findByShortName.mockResolvedValue({ id: 'other-id' });

      await expect(
        service.update('1', { short_name: 'BB' } as any),
      ).rejects.toThrow(ConflictException);
    });

    it('should skip uniqueness check when short_name unchanged', async () => {
      mockRepo.findById.mockResolvedValue(existingItem);
      mockRepo.update.mockResolvedValue(undefined);

      await service.update('1', { short_name: 'AA' } as any);

      expect(mockRepo.findByShortName).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: 'Trip source deleted successfully' });
      expect(mockRepo.softDelete).toHaveBeenCalledWith('1');
    });

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

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