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)('Companies 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 = `co-admin-${runId}@crm-test.local`;
  const salesEmail = `co-sales-${runId}@crm-test.local`;

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

  let adminToken = '';
  let salesToken = '';
  let adminId = '';
  let companyId = '';
  let protectedCompanyId = '';

  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', 'email').create({
      firstName: 'Admin',
      lastName: 'Company',
      email: adminEmail,
      passwordHash,
      role: 'ADMIN',
      isActive: true,
    });
    adminId = admin.id;
    createdUserIds.push(admin.id);

    const sales = await db.orm.public.User.select('id', 'email').create({
      firstName: 'Sales',
      lastName: 'Company',
      email: salesEmail,
      passwordHash,
      role: 'SALES_USER',
      isActive: true,
    });
    createdUserIds.push(sales.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();

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

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

  afterAll(async () => {
    if (db) {
      for (const id of createdLeadIds.reverse()) {
        try {
          await db.orm.public.Lead.where((l) => l.id.eq(id)).delete();
        } catch {
          // best-effort cleanup
        }
      }
      for (const id of createdCompanyIds.reverse()) {
        try {
          await db.orm.public.Company.where((c) => c.id.eq(id)).delete();
        } catch {
          // best-effort cleanup
        }
      }
      for (const id of createdUserIds.reverse()) {
        try {
          await db.orm.public.User.where((u) => u.id.eq(id)).delete();
        } catch {
          // best-effort cleanup
        }
      }
      await db.close();
    }
    if (app) {
      await app.close();
    }
  });

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

  it('creates a company with normalized fields', async () => {
    const res = await request(app.getHttpServer())
      .post('/companies')
      .set('Authorization', `Bearer ${salesToken}`)
      .send({
        name: ` Acme ${runId} `,
        email: ` Hello@Acme-${runId}.Example `,
        website: ' https://acme.example ',
        industry: 'Software',
      })
      .expect(201);

    companyId = res.body.id;
    createdCompanyIds.push(companyId);

    expect(res.body.name).toBe(`Acme ${runId}`);
    expect(res.body.email).toBe(`hello@acme-${runId}.example`);
    expect(res.body.website).toBe('https://acme.example');
    expect(res.body).not.toHaveProperty('leads');
    expect(res.body).not.toHaveProperty('passwordHash');
  });

  it('lists, searches, and paginates companies', async () => {
    const list = await request(app.getHttpServer())
      .get('/companies?page=1&limit=20')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

    expect(list.body.data).toBeInstanceOf(Array);
    expect(list.body.meta).toMatchObject({ page: 1, limit: 20 });
    expect(list.body.data[0]).not.toHaveProperty('passwordHash');

    const search = await request(app.getHttpServer())
      .get(`/companies?search=Acme%20${runId}&page=1&limit=10`)
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(200);

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

  it('gets a company by id and returns 404 when missing', async () => {
    const found = await request(app.getHttpServer())
      .get(`/companies/${companyId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

    expect(found.body.id).toBe(companyId);

    await request(app.getHttpServer())
      .get('/companies/00000000-0000-0000-0000-000000000000')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(404);
  });

  it('updates a company', async () => {
    const res = await request(app.getHttpServer())
      .patch(`/companies/${companyId}`)
      .set('Authorization', `Bearer ${salesToken}`)
      .send({ industry: 'Fintech' })
      .expect(200);

    expect(res.body.industry).toBe('Fintech');
  });

  it('forbids sales users from deleting companies', async () => {
    await request(app.getHttpServer())
      .delete(`/companies/${companyId}`)
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(403);
  });

  it('returns 409 when deleting a company that has leads', async () => {
    const protectedCompany = await request(app.getHttpServer())
      .post('/companies')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ name: `Protected ${runId}` })
      .expect(201);

    protectedCompanyId = protectedCompany.body.id;
    createdCompanyIds.push(protectedCompanyId);

    const lead = await db.orm.public.Lead.select('id').create({
      firstName: 'Lead',
      lastName: 'Test',
      createdById: adminId,
      assignedToId: adminId,
      companyId: protectedCompanyId,
      status: 'NEW',
      source: 'OTHER',
    });
    createdLeadIds.push(lead.id);

    await request(app.getHttpServer())
      .delete(`/companies/${protectedCompanyId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(409);

    const stillThere = await db.orm.public.Company.select('id')
      .where((c) => c.id.eq(protectedCompanyId))
      .first();
    expect(stillThere).toBeTruthy();

    const leadStillThere = await db.orm.public.Lead.select('id')
      .where((l) => l.id.eq(lead.id))
      .first();
    expect(leadStillThere).toBeTruthy();
  });

  it('allows admin to delete a company without leads', async () => {
    await request(app.getHttpServer())
      .delete(`/companies/${companyId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(204);

    createdCompanyIds.splice(createdCompanyIds.indexOf(companyId), 1);

    await request(app.getHttpServer())
      .get(`/companies/${companyId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(404);
  });
});

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