import 'dotenv/config';
import 'temporal-polyfill/full/global';
import { randomUUID } from 'node:crypto';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test, type TestingModule } from '@nestjs/testing';
import * as bcrypt from 'bcrypt';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';

process.env['NODE_ENV'] = 'test';
process.env['ALLOW_PUBLIC_REGISTRATION'] =
  process.env['ALLOW_PUBLIC_REGISTRATION'] ?? 'false';
if (!process.env['JWT_SECRET'] || process.env['JWT_SECRET'].length < 32) {
  process.env['JWT_SECRET'] = 'test-jwt-secret-minimum-32-characters!!';
}
process.env['JWT_EXPIRES_IN'] = process.env['JWT_EXPIRES_IN'] ?? '1d';
process.env['FRONTEND_URL'] =
  process.env['FRONTEND_URL'] ?? 'http://127.0.0.1:5173';
process.env['HOST'] = process.env['HOST'] ?? '127.0.0.1';
process.env['PORT'] = process.env['PORT'] ?? '3000';

const databaseUrl =
  process.env['TEST_DATABASE_URL'] ?? process.env['DATABASE_URL'];
const shouldRun = Boolean(databaseUrl && databaseUrl.trim() !== '');

describe.skipIf(!shouldRun)('Leads integration (PostgreSQL)', () => {
  let app: INestApplication;
  let db: typeof import('../src/prisma/db.js').db;
  const runId = randomUUID().slice(0, 8);
  const password = 'Password123!';

  const adminEmail = `lead-admin-${runId}@crm-test.local`;
  const salesEmail = `lead-sales-${runId}@crm-test.local`;
  const otherSalesEmail = `lead-sales2-${runId}@crm-test.local`;

  const createdUserIds: string[] = [];
  const createdCompanyIds: string[] = [];
  const createdLeadIds: string[] = [];
  const createdActivityIds: string[] = [];

  let adminToken = '';
  let salesToken = '';
  let otherSalesToken = '';
  let adminId = '';
  let salesId = '';
  let otherSalesId = '';
  let companyId = '';
  let leadId = '';

  beforeAll(async () => {
    process.env['DATABASE_URL'] = databaseUrl!;

    const { AppModule } = await import('../src/app.module.js');
    const prisma = await import('../src/prisma/db.js');
    db = prisma.db;

    const passwordHash = await bcrypt.hash(password, 10);

    const admin = await db.orm.public.User.select('id').create({
      firstName: 'Admin',
      lastName: 'Lead',
      email: adminEmail,
      passwordHash,
      role: 'ADMIN',
      isActive: true,
    });
    adminId = admin.id;
    createdUserIds.push(admin.id);

    const sales = await db.orm.public.User.select('id').create({
      firstName: 'Sales',
      lastName: 'Lead',
      email: salesEmail,
      passwordHash,
      role: 'SALES_USER',
      isActive: true,
    });
    salesId = sales.id;
    createdUserIds.push(sales.id);

    const otherSales = await db.orm.public.User.select('id').create({
      firstName: 'Other',
      lastName: 'Sales',
      email: otherSalesEmail,
      passwordHash,
      role: 'SALES_USER',
      isActive: true,
    });
    otherSalesId = otherSales.id;
    createdUserIds.push(otherSales.id);

    const company = await db.orm.public.Company.select('id').create({
      name: `Lead Co ${runId}`,
      website: null,
      industry: null,
      phone: null,
      email: null,
      address: null,
    });
    companyId = company.id;
    createdCompanyIds.push(company.id);

    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    app.useGlobalPipes(
      new ValidationPipe({
        whitelist: true,
        forbidNonWhitelisted: true,
        transform: true,
      }),
    );
    await app.init();

    adminToken = (
      await request(app.getHttpServer())
        .post('/auth/login')
        .send({ email: adminEmail, password })
        .expect(201)
    ).body.accessToken;

    salesToken = (
      await request(app.getHttpServer())
        .post('/auth/login')
        .send({ email: salesEmail, password })
        .expect(201)
    ).body.accessToken;

    otherSalesToken = (
      await request(app.getHttpServer())
        .post('/auth/login')
        .send({ email: otherSalesEmail, password })
        .expect(201)
    ).body.accessToken;
  }, 60_000);

  afterAll(async () => {
    if (db) {
      for (const id of createdActivityIds.reverse()) {
        try {
          await db.orm.public.Activity.where((a) => a.id.eq(id)).delete();
        } catch {
          // best-effort
        }
      }
      // Activities cascade from lead delete, but clean leads explicitly.
      for (const id of createdLeadIds.reverse()) {
        try {
          await db.orm.public.Lead.where((l) => l.id.eq(id)).delete();
        } catch {
          // best-effort
        }
      }
      for (const id of createdCompanyIds.reverse()) {
        try {
          await db.orm.public.Company.where((c) => c.id.eq(id)).delete();
        } catch {
          // best-effort
        }
      }
      for (const id of createdUserIds.reverse()) {
        try {
          await db.orm.public.User.where((u) => u.id.eq(id)).delete();
        } catch {
          // best-effort
        }
      }
      await db.close();
    }
    if (app) {
      await app.close();
    }
  });

  it('rejects unauthenticated access', async () => {
    await request(app.getHttpServer()).get('/leads').expect(401);
  });

  it('creates a lead with immutable ownership from JWT', async () => {
    const res = await request(app.getHttpServer())
      .post('/leads')
      .set('Authorization', `Bearer ${salesToken}`)
      .send({
        firstName: ' Jane ',
        lastName: 'Doe',
        email: ` Jane-${runId}@Example.com `,
        source: 'WEBSITE',
        companyId,
      })
      .expect(201);

    leadId = res.body.id;
    createdLeadIds.push(leadId);

    expect(res.body.createdById).toBe(salesId);
    expect(res.body.assignedToId).toBe(salesId);
    expect(res.body.companyId).toBe(companyId);
    expect(res.body.email).toBe(`jane-${runId}@example.com`);
    expect(res.body).not.toHaveProperty('passwordHash');

    const activities = await db.orm.public.Activity.select('id', 'title')
      .where((a) => a.leadId.eq(leadId))
      .all();
    expect(activities.some((a) => a.title === 'Lead created')).toBe(true);
    createdActivityIds.push(...activities.map((a) => a.id));
  });

  it('rejects client-supplied createdById / assignedToId', async () => {
    await request(app.getHttpServer())
      .post('/leads')
      .set('Authorization', `Bearer ${salesToken}`)
      .send({
        firstName: 'Blocked',
        createdById: adminId,
        assignedToId: adminId,
      })
      .expect(400);
  });

  it('rejects invalid companyId', async () => {
    await request(app.getHttpServer())
      .post('/leads')
      .set('Authorization', `Bearer ${salesToken}`)
      .send({
        firstName: 'Bad',
        companyId: '11111111-1111-4111-8111-111111111111',
      })
      .expect(404);
  });

  it('lists/filters/searches with pagination', async () => {
    const list = await request(app.getHttpServer())
      .get('/leads?page=1&limit=20&status=NEW&source=WEBSITE')
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(200);

    expect(list.body.meta).toMatchObject({ page: 1, limit: 20 });
    expect(
      list.body.data.some((l: { id: string }) => l.id === leadId),
    ).toBe(true);

    const search = await request(app.getHttpServer())
      .get(`/leads?search=Jane&companyId=${companyId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

    expect(
      search.body.data.some((l: { id: string }) => l.id === leadId),
    ).toBe(true);
  });

  it('enforces sales ownership on get/update', async () => {
    await request(app.getHttpServer())
      .get(`/leads/${leadId}`)
      .set('Authorization', `Bearer ${otherSalesToken}`)
      .expect(403);

    await request(app.getHttpServer())
      .patch(`/leads/${leadId}`)
      .set('Authorization', `Bearer ${otherSalesToken}`)
      .send({ firstName: 'Nope' })
      .expect(403);

    const updated = await request(app.getHttpServer())
      .patch(`/leads/${leadId}`)
      .set('Authorization', `Bearer ${salesToken}`)
      .send({ firstName: 'Janet', notes: 'Follow up' })
      .expect(200);

    expect(updated.body.firstName).toBe('Janet');
    expect(updated.body.createdById).toBe(salesId);
  });

  it('updates status and records activity', async () => {
    const res = await request(app.getHttpServer())
      .patch(`/leads/${leadId}/status`)
      .set('Authorization', `Bearer ${salesToken}`)
      .send({ status: 'CONTACTED' })
      .expect(200);

    expect(res.body.status).toBe('CONTACTED');

    const activities = await db.orm.public.Activity.select('id', 'title')
      .where((a) => a.leadId.eq(leadId))
      .all();
    expect(activities.some((a) => a.title === 'Lead status changed')).toBe(
      true,
    );
    for (const activity of activities) {
      if (!createdActivityIds.includes(activity.id)) {
        createdActivityIds.push(activity.id);
      }
    }
  });

  it('allows current assignee to reassign; forbids unrelated sales', async () => {
    await request(app.getHttpServer())
      .patch(`/leads/${leadId}/assign`)
      .set('Authorization', `Bearer ${otherSalesToken}`)
      .send({ assignedToId: otherSalesId })
      .expect(403);

    const res = await request(app.getHttpServer())
      .patch(`/leads/${leadId}/assign`)
      .set('Authorization', `Bearer ${salesToken}`)
      .send({ assignedToId: otherSalesId })
      .expect(200);

    expect(res.body.assignedToId).toBe(otherSalesId);
    expect(res.body.createdById).toBe(salesId);

    const activities = await db.orm.public.Activity.select('id', 'title')
      .where((a) => a.leadId.eq(leadId))
      .all();
    expect(activities.some((a) => a.title === 'Lead reassigned')).toBe(true);
  });

  it('admin can access and manage any lead', async () => {
    const res = await request(app.getHttpServer())
      .get(`/leads/${leadId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

    expect(res.body.id).toBe(leadId);

    await request(app.getHttpServer())
      .patch(`/leads/${leadId}/assign`)
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ assignedToId: salesId })
      .expect(200);
  });

  it('returns 404 for missing lead', async () => {
    await request(app.getHttpServer())
      .get('/leads/00000000-0000-0000-0000-000000000000')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(404);
  });
});

describe.skipIf(shouldRun)('Leads integration skipped', () => {
  it('skips when DATABASE_URL / TEST_DATABASE_URL is not configured', () => {
    expect(shouldRun).toBe(false);
  });
});
