/**
 * Organizations API
 *
 * Organization-related API calls
 */

import { apiClient } from './client';

export interface Organization {
  id: string;
  name: string;
  type: 'freight_forwarder' | 'carrier' | 'shipper';
  scac?: string;
  address: {
    street: string;
    city: string;
    postalCode: string;
    country: string;
  };
  contactEmail: string;
  contactPhone: string;
  logoUrl?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface CreateOrganizationRequest {
  name: string;
  type: 'freight_forwarder' | 'carrier' | 'shipper';
  scac?: string;
  address: {
    street: string;
    city: string;
    postalCode: string;
    country: string;
  };
  contactEmail: string;
  contactPhone: string;
}

export interface UpdateOrganizationRequest {
  name?: string;
  scac?: string;
  address?: {
    street: string;
    city: string;
    postalCode: string;
    country: string;
  };
  contactEmail?: string;
  contactPhone?: string;
  isActive?: boolean;
}

export const organizationsApi = {
  /**
   * Get current user's organization
   */
  async getCurrent(): Promise<Organization> {
    return apiClient.get<Organization>('/api/v1/organizations/current');
  },

  /**
   * Get organization by ID
   */
  async getById(id: string): Promise<Organization> {
    return apiClient.get<Organization>(`/api/v1/organizations/${id}`);
  },

  /**
   * Update organization
   */
  async update(id: string, data: UpdateOrganizationRequest): Promise<Organization> {
    return apiClient.patch<Organization>(`/api/v1/organizations/${id}`, data);
  },

  /**
   * Upload organization logo
   */
  async uploadLogo(id: string, file: File): Promise<{ logoUrl: string }> {
    const formData = new FormData();
    formData.append('logo', file);

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/organizations/${id}/logo`,
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
        },
        body: formData,
      }
    );

    if (!response.ok) {
      throw new Error('Failed to upload logo');
    }

    return response.json();
  },

  /**
   * List all organizations (admin only)
   */
  async list(): Promise<Organization[]> {
    return apiClient.get<Organization[]>('/api/v1/organizations');
  },
};
