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

// Transform snake_case database columns to camelCase for TypeScript interface
function transformCompany(row: any) {
  return {
    id: Number(row.id),
    companyName: row.company_name,
    companyType: row.company_type,
    isActive: row.is_active,
    phone: row.phone,
    fax: row.fax,
    webAddress: row.web_address,
    address1: row.address1,
    address2: row.address2,
    city: row.city,
    state: row.state,
    postalCode: row.postal_code,
    country: row.country,
    createdTime: row.created_time,
    lastModifiedTime: row.last_modified_time,
  };
}

export async function GET(request: NextRequest) {
  try {
    const result = await postgresClient.query(
      'SELECT * FROM companies WHERE is_active = true AND company_type = 1 ORDER BY company_name'
    );
    
    const companies = result.rows.map(transformCompany);
    
    return NextResponse.json({ companies });
  } catch (error) {
    console.error('Error fetching companies from database:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to fetch companies' },
      { status: 500 }
    );
  }
}
