/// <reference types="jest" />
import { ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';

// Mock nestjs-prisma 模块
jest.mock('nestjs-prisma', () => ({
  PrismaService: jest.fn(),
}));

import { PrismaService } from 'nestjs-prisma';
import { PageResourceService } from './pageResource.service';

// Mock PrismaService
const mockPrismaService = {
  pageResource: {
    create: jest.fn(),
    createMany: jest.fn(),
    findMany: jest.fn(),
    findUnique: jest.fn(),
    update: jest.fn(),
    updateMany: jest.fn(),
    delete: jest.fn(),
    deleteMany: jest.fn(),
    count: jest.fn(),
    groupBy: jest.fn(),
    aggregate: jest.fn(),
  },
};

// Mock Logger
const mockLogger = {
  child: jest.fn().mockReturnThis(),
  info: jest.fn(),
  error: jest.fn(),
  warn: jest.fn(),
  debug: jest.fn(),
};

// Mock ConfigService
const mockConfigService = {
  get: jest.fn(),
};

describe('PageResourceService', () => {
  let service: PageResourceService;
  let prisma: typeof mockPrismaService;

  beforeEach(async () => {
    // 每个测试前重置所有 mock
    jest.clearAllMocks();

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        PageResourceService,
        { provide: PrismaService, useValue: mockPrismaService },
        { provide: ConfigService, useValue: mockConfigService },
        { provide: WINSTON_MODULE_PROVIDER, useValue: mockLogger },
      ],
    })
      // 兜底：自动 mock 任何未显式提供的依赖
      // （例如手工给 service 增加的额外依赖：RoleService、其他 Service 等）
      .useMocker(() => ({}))
      .compile();

    service = module.get<PageResourceService>(PageResourceService);
    prisma = mockPrismaService;
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });

  describe('createOne', () => {
    it('should create a single pageResource record', async () => {
      const createArgs = {
        data: {
          actions: {},
          creator: 'test_creator',
        },
      } as any;
      const expectedResult = { id: 1, ...createArgs.data };

      prisma.pageResource.create.mockResolvedValue(expectedResult);

      const result = await service.createOne(createArgs);

      expect(prisma.pageResource.create).toHaveBeenCalledWith(createArgs);
      expect(prisma.pageResource.create).toHaveBeenCalledTimes(1);
      expect(result).toEqual(expectedResult);
    });

    it('should throw error when create fails', async () => {
      const createArgs = {
        data: {
          actions: {},
          creator: 'test_creator',
        },
      } as any;
      const error = new Error('Database connection failed');

      prisma.pageResource.create.mockRejectedValue(error);

      await expect(service.createOne(createArgs)).rejects.toThrow(
        'Database connection failed',
      );
    });
  });

  describe('createMany', () => {
    it('should create multiple pageResource records with skipDuplicates', async () => {
      const data = [
        {
          actions: {},
          creator: 'test_creator',
        },
        {
          actions: {},
          creator: 'test_creator',
        },
      ] as any;
      const expectedResult = { count: 2 };

      prisma.pageResource.createMany.mockResolvedValue(expectedResult);

      const result = await service.createMany(data);

      expect(prisma.pageResource.createMany).toHaveBeenCalledWith({
        data,
        skipDuplicates: true,
      });
      expect(result).toEqual(expectedResult);
    });
  });

  describe('findMany', () => {
    it('should return entities with itemCount', async () => {
      const findArgs = {
        where: {},
        take: 10,
        skip: 0,
      } as any;
      const mockEntities = [{ id: 1 }, { id: 2 }];

      prisma.pageResource.count.mockResolvedValue(2);
      prisma.pageResource.findMany.mockResolvedValue(mockEntities);

      const result = await service.findMany(findArgs);

      expect(prisma.pageResource.count).toHaveBeenCalledWith({
        where: findArgs.where,
      });
      expect(prisma.pageResource.findMany).toHaveBeenCalledWith(findArgs);
      expect(result).toEqual({
        itemCount: 2,
        entities: mockEntities,
      });
    });

    it('should return empty result when no records found', async () => {
      const findArgs = { where: {} } as any;

      prisma.pageResource.count.mockResolvedValue(0);
      prisma.pageResource.findMany.mockResolvedValue([]);

      const result = await service.findMany(findArgs);

      expect(result).toEqual({ itemCount: 0, entities: [] });
    });
  });

  describe('findUnique', () => {
    it('should find a single pageResource record by id', async () => {
      const id = 1;
      const select = { id: true };
      const expectedResult = { id: 1 };

      prisma.pageResource.findUnique.mockResolvedValue(expectedResult);

      const result = await service.findUnique(id, select);

      expect(prisma.pageResource.findUnique).toHaveBeenCalledWith({
        where: { id },
        select,
      });
      expect(result).toEqual(expectedResult);
    });

    it('should return null when record not found', async () => {
      prisma.pageResource.findUnique.mockResolvedValue(null);

      const result = await service.findUnique(1, { id: true });

      expect(result).toBeNull();
    });
  });

  describe('updateUnique', () => {
    it('should update a single pageResource record', async () => {
      const id = 1;
      const data = {
        actions: {},
        creator: 'test_creator',
      } as any;
      const expectedResult = { id: 1, ...data };

      prisma.pageResource.update.mockResolvedValue(expectedResult);

      const result = await service.updateUnique(id, data);

      expect(prisma.pageResource.update).toHaveBeenCalledWith({
        where: { id },
        data,
      });
      expect(result).toEqual(expectedResult);
    });
  });

  describe('updateMany', () => {
    it('should update multiple pageResource records', async () => {
      const updateArgs = {
        where: {},
        data: {
          actions: {},
          creator: 'test_creator',
        },
      } as any;
      const expectedResult = { count: 5 };

      prisma.pageResource.updateMany.mockResolvedValue(expectedResult);

      const result = await service.updateMany(updateArgs);

      expect(prisma.pageResource.updateMany).toHaveBeenCalledWith(updateArgs);
      expect(result).toEqual(expectedResult);
    });
  });

  describe('deleteUnique', () => {
    it('should delete a single pageResource record and return count', async () => {
      const id = 1;

      prisma.pageResource.delete.mockResolvedValue({ id: 1 });

      const result = await service.deleteUnique(id);

      expect(prisma.pageResource.delete).toHaveBeenCalledWith({
        where: { id },
      });
      expect(result).toEqual({ count: 1 });
    });
  });

  describe('deleteMany', () => {
    it('should delete multiple pageResource records', async () => {
      const deleteArgs = { where: {} } as any;
      const expectedResult = { count: 3 };

      prisma.pageResource.deleteMany.mockResolvedValue(expectedResult);

      const result = await service.deleteMany(deleteArgs);

      expect(prisma.pageResource.deleteMany).toHaveBeenCalledWith(deleteArgs);
      expect(result).toEqual(expectedResult);
    });
  });

  describe('count', () => {
    it('should count pageResource records with filter', async () => {
      const countArgs = { where: {} } as any;

      prisma.pageResource.count.mockResolvedValue(10);

      const result = await service.count(countArgs);

      expect(prisma.pageResource.count).toHaveBeenCalledWith(countArgs);
      expect(result).toBe(10);
    });

    it('should count all records when no filter provided', async () => {
      prisma.pageResource.count.mockResolvedValue(100);

      const result = await service.count();

      expect(prisma.pageResource.count).toHaveBeenCalledWith(undefined);
      expect(result).toBe(100);
    });
  });

  describe('groupBy', () => {
    it('should group pageResource records by specified field', async () => {
      const groupByArgs = {
        by: ['id'],
        _count: { id: true },
      } as any;
      const expectedResult = [{ id: 1, _count: { id: 50 } }];

      prisma.pageResource.groupBy.mockResolvedValue(expectedResult);

      const result = await service.groupBy(groupByArgs);

      expect(prisma.pageResource.groupBy).toHaveBeenCalledWith(groupByArgs);
      expect(result).toEqual(expectedResult);
    });
  });

  describe('aggregate', () => {
    it('should aggregate pageResource records', async () => {
      const aggregateArgs = {
        _count: true,
        _max: { id: true },
        _min: { id: true },
      } as any;
      const expectedResult = {
        _count: 100,
        _max: { id: 1 },
        _min: { id: 1 },
      };

      prisma.pageResource.aggregate.mockResolvedValue(expectedResult);

      const result = await service.aggregate(aggregateArgs);

      expect(prisma.pageResource.aggregate).toHaveBeenCalledWith(aggregateArgs);
      expect(result).toEqual(expectedResult);
    });
  });
});
