import { Test, TestingModule } from '@nestjs/testing';
import { ConflictException, NotFoundException } from '@nestjs/common';
import { DestinationService } from './destination.service';
import { DestinationRepository } from './repositories/destination.repository';

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

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

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

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

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

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

      const result = await service.findAll();

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

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

  describe('findById', () => {
    it('should return the destination when found', async () => {
      const dest = { id: '1', name: 'Bali' };
      mockRepo.findById.mockResolvedValue(dest);

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

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

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

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

  describe('create', () => {
    const createDto = {
      name: 'Bali',
      short_code: 'BAL',
      country: 'Indonesia',
      city: 'Denpasar',
      currency: 'IDR',
    };

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

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

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

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

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

  describe('update', () => {
    const existingDest = { id: '1', short_code: 'BAL' };

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

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

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

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

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

    it('should throw ConflictException when short_code conflicts with another destination', async () => {
      mockRepo.findById.mockResolvedValue(existingDest);
      mockRepo.findByShortCode.mockResolvedValue({ id: 'other-id' });

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

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

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

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

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

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