import { NextResponse } from 'next/server';
import { postgresClient } from '@/lib/services/postgres-client';

export async function GET() {
  try {
    const result = await postgresClient.query(`
      SELECT da.id, da.account_id, da.name, da.api_hostname,
             da.user_count, da.integration_count, da.edition,
             da.is_parent, da.synced_at, da.created_at,
             da.autotask_company_id,
             c.company_name as autotask_company_name
      FROM duo_accounts da
      LEFT JOIN companies c ON c.id = da.autotask_company_id
      ORDER BY da.is_parent DESC, da.name ASC
    `);

    return NextResponse.json({ accounts: result.rows });
  } catch (error: any) {
    console.error('[DuoAPI] Error fetching accounts:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
