import { Test, TestingModule } from '@nestjs/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { LeadsService } from '../leads/leads.service.js';
import { PrismaService } from '../prisma/prisma.service.js';
import { ActivitiesService } from './activities.service.js';

describe('ActivitiesService', () => {
  let service: ActivitiesService;
  let prisma: {
    db: {
      orm: {
        public: {
          Activity: {
            select: ReturnType<typeof vi.fn>;
          };
        };
      };
    };
  };
  let leadsService: {
    findOne: ReturnType<typeof vi.fn>;
  };

  const currentUser = {
    id: 'user-1',
    firstName: 'Ada',
    lastName: 'Admin',
    email: 'ada@example.com',
    role: 'ADMIN' as const,
    isActive: true,
    createdAt: new Date('2026-01-01T00:00:00.000Z'),
    updatedAt: new Date('2026-01-01T00:00:00.000Z'),
  };

  beforeEach(async () => {
    const activityApi = {
      where: vi.fn().mockReturnThis(),
      orderBy: vi.fn().mockReturnThis(),
      all: vi.fn().mockResolvedValue([]),
      create: vi.fn(),
      first: vi.fn(),
      update: vi.fn(),
    };

    prisma = {
      db: {
        orm: {
          public: {
            Activity: {
              select: vi.fn(() => activityApi),
            },
          },
        },
      },
    };

    leadsService = {
      findOne: vi.fn().mockResolvedValue({ id: 'lead-1', assignedToId: 'user-1' }),
    };

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ActivitiesService,
        { provide: PrismaService, useValue: prisma },
        { provide: LeadsService, useValue: leadsService },
      ],
    }).compile();

    service = module.get(ActivitiesService);
  });

  it('lists activities after verifying lead access', async () => {
    const result = await service.listForLead('lead-1', currentUser);
    expect(leadsService.findOne).toHaveBeenCalledWith('lead-1', currentUser);
    expect(result).toEqual([]);
  });

  it('creates an activity for an accessible lead', async () => {
    const created = {
      id: 'act-1',
      type: 'NOTE',
      title: 'Follow up',
      description: null,
      dueAt: null,
      completedAt: null,
      leadId: 'lead-1',
      userId: 'user-1',
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const activityApi = prisma.db.orm.public.Activity.select();
    activityApi.create.mockResolvedValue(created);

    const result = await service.createForLead(
      'lead-1',
      { type: 'NOTE', title: 'Follow up' },
      currentUser,
    );

    expect(result).toEqual(created);
    expect(activityApi.create).toHaveBeenCalled();
  });

  it('creates a LinkedIn activity type for an accessible lead', async () => {
    const created = {
      id: 'act-2',
      type: 'LINKEDIN',
      title: 'LinkedIn',
      description: 'Sent connection request',
      dueAt: null,
      completedAt: null,
      leadId: 'lead-1',
      userId: 'user-1',
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const activityApi = prisma.db.orm.public.Activity.select();
    activityApi.create.mockResolvedValue(created);

    const result = await service.createForLead(
      'lead-1',
      {
        type: 'LINKEDIN',
        title: 'LinkedIn',
        description: 'Sent connection request',
      },
      currentUser,
    );

    expect(result).toEqual(created);
    expect(activityApi.create).toHaveBeenCalledWith(
      expect.objectContaining({
        type: 'LINKEDIN',
        title: 'LinkedIn',
        description: 'Sent connection request',
      }),
    );
  });
});
