import { Test, type TestingModule } from '@nestjs/testing';
import { ConflictException, NotFoundException } from '@nestjs/common';
import { ActivityService } from './activity.service';
import { ActivityRepository } from './repositories/activity.repository';
import { ActivityTicketRepository } from './repositories/activity-ticket.repository';
import { ActivityMediaRepository } from './repositories/activity-media.repository';
import { MediaService } from '../../common/media/media.service';

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

  const mockRepo = {
    findPaginated: jest.fn(),
    findAllWithDestination: jest.fn(),
    findByIdWithDestination: jest.fn(),
    findByIdWithRelations: jest.fn(),
    findByNameAndDestination: jest.fn(),
    findByShortCode: jest.fn(),
    findById: jest.fn(),
    save: jest.fn(),
    update: jest.fn(),
    softDelete: jest.fn(),
    // Internals consumed by activity_pricing auto-sync — not exercised in unit tests
    getTenantId: jest.fn().mockReturnValue('tenant-1'),
    cls: { get: jest.fn().mockReturnValue(null) },
    repo: { manager: { query: jest.fn().mockResolvedValue([]) } },
  };

  const mockTicketRepo = {
    findByActivityId: jest.fn().mockResolvedValue([]),
    save: jest.fn(),
    update: jest.fn(),
    softDelete: jest.fn(),
  };

  const mockMedia = {
    list: jest.fn().mockResolvedValue([]),
    prepare: jest.fn(),
    sync: jest.fn(),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ActivityService,
        { provide: ActivityRepository, useValue: mockRepo },
        { provide: ActivityTicketRepository, useValue: mockTicketRepo },
        { provide: ActivityMediaRepository, useValue: {} },
        { provide: MediaService, useValue: mockMedia },
      ],
    }).compile();

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

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

  describe('findAll', () => {
    it('should return paginated activities with destinations', async () => {
      const activities = [{ id: '1', name: 'Safari' }];
      const paginated = {
        items: activities,
        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 activities 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 activity when found', async () => {
      const activity = { id: '1', name: 'Safari', tickets: [] };
      mockRepo.findByIdWithRelations.mockResolvedValue(activity);

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

      expect(result).toEqual({ ...activity, media: [] });
      expect(mockRepo.findByIdWithRelations).toHaveBeenCalledWith('1');
    });

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

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

  describe('create', () => {
    const createDto = {
      name: 'Safari',
      destination_id: 'dest-1',
      address: '123 Main St',
      time_slot: 'morning',
      contact_person: 'John',
    };

    it('should create and return success response', async () => {
      mockRepo.findByNameAndDestination.mockResolvedValue(null);
      // short_code is auto-derived → helper probes findByShortCode.
      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: 'Activity created successfully' });
      expect(mockRepo.save).toHaveBeenCalledTimes(1);
      // createDto.name (whatever it is) → derived. Just assert non-empty.
      expect(mockRepo.save.mock.calls[0][0].short_code).toMatch(/^[A-Z0-9]+$/);
    });

    it('should throw ConflictException when name+destination already exists', async () => {
      mockRepo.findByNameAndDestination.mockResolvedValue({ id: 'existing' });

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

  describe('update', () => {
    const existingActivity = { id: '1', name: 'Safari', destination_id: 'dest-1' };

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

      const result = await service.update('1', { address: 'New Address' } as any);

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

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

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

    it('should throw ConflictException when name+destination conflicts with another activity', async () => {
      mockRepo.findById.mockResolvedValue(existingActivity);
      mockRepo.findByNameAndDestination.mockResolvedValue({ id: 'other-id' });

      await expect(service.update('1', { name: 'New Name' } as any)).rejects.toThrow(
        ConflictException,
      );
    });
  });

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

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

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

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

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