/* eslint-disable */
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { NextResponse } from 'next/server';
import { Pool } from 'pg';
import jwt from 'jsonwebtoken';
import { cookies } from 'next/headers';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL || 'postgresql://jumpa_admin:JumpaS3cur3%21%40%23@127.0.0.1:5432/jumpadb',
});

export async function GET(req: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;

    if (!token) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    let decoded: any;
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET as string);
    } catch (e) {
      return NextResponse.json({ error: 'Invalid Token' }, { status: 401 });
    }

    const currentUserEmail = decoded.email;
    const currentTenantId = decoded.tenantId;
    const allowCrossGroup = decoded.allowCrossGroup === true;

    // ALGORITMA ISOLASI MULTI-TENANT (CLOSED GROUP)
    let result;
    if (allowCrossGroup) {
       // Cross Group Aktif: Bisa lihat sesama tenant + tenant lain yang juga open
       result = await pool.query(`
         SELECT u.email, u.role, u.tenant_id 
         FROM users u
         JOIN tenants t ON u.tenant_id = t.id
         WHERE u.email != $1 AND (u.tenant_id = $2 OR t.allow_cross_group = true)
       `, [currentUserEmail, currentTenantId]);
    } else {
       // Closed Group Aktif (Default Enterprise): HANYA bisa lihat orang di perusahaan yang sama
       result = await pool.query(`
         SELECT email, role, tenant_id 
         FROM users 
         WHERE email != $1 AND tenant_id = $2
       `, [currentUserEmail, currentTenantId]);
    }

    return NextResponse.json({ users: result.rows }, { status: 200 });
  } catch (error) {
    console.error('[API USERS ERROR]', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

