import 'dotenv/config';
import 'temporal-polyfill/full/global';
import { randomUUID } from 'node:crypto';
import {
  INestApplication,
  ValidationPipe,
  type NestApplicationOptions,
} 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'] ?? 'true';
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)('Auth & Users integration (PostgreSQL)', () => {
  let app: INestApplication;
  let db: typeof import('../src/prisma/db.js').db;
  const runId = randomUUID().slice(0, 8);
  const createdUserIds: string[] = [];

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

  let adminToken = '';
  let salesToken = '';
  let adminId = '';
  let salesId = '';
  let otherSalesId = '';

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

  afterAll(async () => {
    if (db) {
      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('logs in admin', async () => {
    const res = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: adminEmail, password })
      .expect(201);

    expect(res.body.accessToken).toBeTruthy();
    expect(res.body.user.email).toBe(adminEmail);
    expect(res.body.user).not.toHaveProperty('passwordHash');
    adminToken = res.body.accessToken;
  });

  it('rejects wrong password', async () => {
    await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: adminEmail, password: 'wrong-password' })
      .expect(401);
  });

  it('rejects missing JWT on /auth/me', async () => {
    await request(app.getHttpServer()).get('/auth/me').expect(401);
  });

  it('rejects invalid JWT on /auth/me', async () => {
    await request(app.getHttpServer())
      .get('/auth/me')
      .set('Authorization', 'Bearer not-a-valid-token')
      .expect(401);
  });

  it('returns current user for valid JWT', async () => {
    const res = await request(app.getHttpServer())
      .get('/auth/me')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

    expect(res.body.email).toBe(adminEmail);
    expect(res.body.role).toBe('ADMIN');
  });

  it('admin provisions a sales user', async () => {
    const res = await request(app.getHttpServer())
      .post('/users')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({
        firstName: 'Sales',
        lastName: 'User',
        email: salesEmail,
        password,
        role: 'SALES_USER',
      })
      .expect(201);

    salesId = res.body.id;
    createdUserIds.push(salesId);
    expect(res.body.email).toBe(salesEmail);
    expect(res.body).not.toHaveProperty('passwordHash');
  });

  it('rejects duplicate email registration/provisioning', async () => {
    await request(app.getHttpServer())
      .post('/users')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({
        firstName: 'Dup',
        lastName: 'User',
        email: salesEmail,
        password,
      })
      .expect(409);
  });

  it('registers via public endpoint when enabled', async () => {
    if (process.env['ALLOW_PUBLIC_REGISTRATION'] !== 'true') {
      return;
    }

    const email = `public-${runId}@crm-test.local`;
    const res = await request(app.getHttpServer())
      .post('/auth/register')
      .send({
        firstName: 'Public',
        lastName: 'User',
        email,
        password,
      })
      .expect(201);

    createdUserIds.push(res.body.id);
    expect(res.body.role).toBe('SALES_USER');
  });

  it('sales user can login and access own profile via /auth/me', async () => {
    const login = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: salesEmail, password })
      .expect(201);

    salesToken = login.body.accessToken;

    const me = await request(app.getHttpServer())
      .get('/auth/me')
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(200);

    expect(me.body.id).toBe(salesId);
  });

  it('sales user cannot access user-management endpoints', async () => {
    await request(app.getHttpServer())
      .get('/users?page=1&limit=20')
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(403);

    await request(app.getHttpServer())
      .get(`/users/${salesId}`)
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(403);

    await request(app.getHttpServer())
      .get(`/users/${adminId}`)
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(403);

    await request(app.getHttpServer())
      .post('/users')
      .set('Authorization', `Bearer ${salesToken}`)
      .send({
        firstName: 'Nope',
        lastName: 'User',
        email: `blocked-${runId}@crm-test.local`,
        password,
      })
      .expect(403);
  });

  it('admin can list users; sales can list assignees only', async () => {
    const adminList = await request(app.getHttpServer())
      .get('/users?page=1&limit=20')
      .set('Authorization', `Bearer ${adminToken}`)
      .expect(200);

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

    const salesAssignees = await request(app.getHttpServer())
      .get('/users/assignees?page=1&limit=20')
      .set('Authorization', `Bearer ${salesToken}`)
      .expect(200);

    expect(salesAssignees.body.data).toBeInstanceOf(Array);
    expect(
      salesAssignees.body.data.every((u: { isActive: boolean }) => u.isActive),
    ).toBe(true);
  });

  it('admin can update user; sales cannot', async () => {
    await request(app.getHttpServer())
      .patch(`/users/${salesId}`)
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ firstName: 'SalesUpdated' })
      .expect(200);

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

  it('admin can change status; sales cannot; inactive cannot login', async () => {
    const other = await request(app.getHttpServer())
      .post('/users')
      .set('Authorization', `Bearer ${adminToken}`)
      .send({
        firstName: 'Other',
        lastName: 'Sales',
        email: otherSalesEmail,
        password,
      })
      .expect(201);

    otherSalesId = other.body.id;
    createdUserIds.push(otherSalesId);

    await request(app.getHttpServer())
      .patch(`/users/${otherSalesId}/status`)
      .set('Authorization', `Bearer ${salesToken}`)
      .send({ isActive: false })
      .expect(403);

    await request(app.getHttpServer())
      .patch(`/users/${otherSalesId}/status`)
      .set('Authorization', `Bearer ${adminToken}`)
      .send({ isActive: false })
      .expect(200);

    await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: otherSalesEmail, password })
      .expect(401);
  });

  it('prevents deactivating the last active admin', async () => {
    const activeAdmins = await db.orm.public.User.select('id')
      .where((u) => u.role.eq('ADMIN'))
      .where((u) => u.isActive.eq(true))
      .all();

    const otherAdminIds = activeAdmins
      .map((row) => row.id)
      .filter((id) => id !== adminId);

    for (const id of otherAdminIds) {
      await db.orm.public.User.where((u) => u.id.eq(id)).update({
        isActive: false,
      });
    }

    try {
      await request(app.getHttpServer())
        .patch(`/users/${adminId}/status`)
        .set('Authorization', `Bearer ${adminToken}`)
        .send({ isActive: false })
        .expect(409);
    } finally {
      for (const id of otherAdminIds) {
        await db.orm.public.User.where((u) => u.id.eq(id)).update({
          isActive: true,
        });
      }
    }
  });
});

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