/**
 * API Types
 *
 * TypeScript types for all API requests and responses
 */

// ============================================================================
// Authentication
// ============================================================================

export interface RegisterOrganizationData {
  name: string;
  type: OrganizationType;
  siren: string;
  siret?: string;
  street: string;
  city: string;
  state?: string;
  postalCode: string;
  country: string;
  scac?: string;
}

export interface RegisterRequest {
  email: string;
  password: string;
  firstName: string;
  lastName: string;
  invitationToken?: string; // For invited users (token-based)
  organizationId?: string; // For invited users (ID-based)
  organization?: RegisterOrganizationData; // For new users
}

export interface LoginRequest {
  email: string;
  password: string;
}

export interface AuthResponse {
  accessToken: string;
  refreshToken: string;
  user: UserPayload;
}

export interface RefreshTokenRequest {
  refreshToken: string;
}

export interface UserPayload {
  id?: string; // From JWT 'sub' or direct ID
  sub?: string; // JWT subject
  email: string;
  firstName?: string;
  lastName?: string;
  role: UserRole;
  organizationId: string;
}

export type UserRole = 'ADMIN' | 'MANAGER' | 'USER' | 'VIEWER';

// ============================================================================
// Users
// ============================================================================

export interface CreateUserRequest {
  email: string;
  password: string;
  firstName: string;
  lastName: string;
  role: UserRole;
  organizationId?: string;
}

export interface UpdateUserRequest {
  firstName?: string;
  lastName?: string;
  role?: UserRole;
  isActive?: boolean;
}

export interface UpdatePasswordRequest {
  currentPassword: string;
  newPassword: string;
}

export interface UserResponse {
  id: string;
  email: string;
  firstName: string;
  lastName: string;
  role: UserRole;
  organizationId: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface UserListResponse {
  users: UserResponse[];
  total: number;
  page: number;
  pageSize: number;
}

// ============================================================================
// Organizations
// ============================================================================

export type OrganizationType = 'FREIGHT_FORWARDER' | 'CARRIER' | 'SHIPPER';

export interface CreateOrganizationRequest {
  name: string;
  type: OrganizationType;
  address: {
    street: string;
    city: string;
    state?: string;
    postalCode: string;
    country: string;
  };
  siren?: string;
  siret?: string;
  eori?: string;
  scac?: string;
  contact_email?: string;
  contact_phone?: string;
  logo_url?: string;
}

export interface UpdateOrganizationRequest {
  name?: string;
  siren?: string;
  siret?: string;
  eori?: string;
  contact_phone?: string;
  contact_email?: string;
  address?: {
    street: string;
    city: string;
    state?: string;
    postalCode: string;
    country: string;
  };
  logoUrl?: string;
  isActive?: boolean;
}

export interface OrganizationAddress {
  street: string;
  city: string;
  state?: string;
  postalCode: string;
  country: string;
}

export interface OrganizationResponse {
  id: string;
  name: string;
  type: OrganizationType;
  scac?: string | null;
  siren?: string | null;
  eori?: string | null;
  siret?: string | null;
  siretVerified?: boolean;
  statusBadge?: 'none' | 'silver' | 'gold' | 'platinium';
  contact_phone?: string | null;
  contact_email?: string | null;
  address: OrganizationAddress;
  logoUrl?: string | null;
  documents: any[];
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface OrganizationListResponse {
  organizations: OrganizationResponse[];
  total: number;
  page: number;
  pageSize: number;
}

// ============================================================================
// Bookings
// ============================================================================

export type BookingStatus =
  | 'DRAFT'
  | 'PENDING_CONFIRMATION'
  | 'CONFIRMED'
  | 'IN_TRANSIT'
  | 'DELIVERED'
  | 'CANCELLED';

export interface CreateBookingRequest {
  rateQuoteId?: string;
  carrier: string;
  origin: string;
  destination: string;
  containerType: string;
  volumeCBM: number;
  weightKG: number;
  shipperName: string;
  shipperAddress: string;
  shipperContact: string;
  consigneeName: string;
  consigneeAddress: string;
  consigneeContact: string;
  cargoDescription: string;
  estimatedDeparture?: string;
}

export interface BookingResponse {
  id: string;
  bookingNumber: string;
  status: BookingStatus;
  carrier: string;
  origin: string;
  destination: string;
  containerType: string;
  volumeCBM: number;
  weightKG: number;
  shipperName: string;
  shipperAddress: string;
  shipperContact: string;
  consigneeName: string;
  consigneeAddress: string;
  consigneeContact: string;
  cargoDescription: string;
  specialInstructions?: string;
  estimatedDeparture: string | null;
  shipper?: {
    name: string;
    contactName?: string;
    contactEmail?: string;
    contactPhone?: string;
    address?: string;
  };
  consignee?: {
    name: string;
    contactName?: string;
    contactEmail?: string;
    contactPhone?: string;
    address?: string;
  };
  containers?: Array<{
    id: string;
    type: string;
    containerNumber?: string;
    sealNumber?: string;
    vgm?: number;
  }>;
  createdAt: string;
  updatedAt: string;
}

export interface BookingListResponse {
  bookings: BookingResponse[];
  total: number;
  page: number;
  pageSize: number;
}

export interface BookingFilterParams {
  status?: BookingStatus | BookingStatus[];
  startDate?: string;
  endDate?: string;
  carrier?: string;
  originPort?: string;
  destinationPort?: string;
  shipper?: string;
  consignee?: string;
  sortBy?: string;
  sortOrder?: 'ASC' | 'DESC';
  page?: number;
  limit?: number;
}

export interface BookingExportRequest {
  format: 'CSV' | 'EXCEL' | 'JSON';
  filters?: BookingFilterParams;
}

// ============================================================================
// Notifications
// ============================================================================

export type NotificationType =
  | 'booking_created'
  | 'booking_updated'
  | 'booking_cancelled'
  | 'booking_confirmed'
  | 'rate_quote_expiring'
  | 'document_uploaded'
  | 'system_announcement'
  | 'user_invited'
  | 'organization_update'
  | 'csv_booking_accepted'
  | 'csv_booking_rejected'
  | 'csv_booking_request_sent';

export type NotificationPriority = 'low' | 'medium' | 'high' | 'urgent';

export interface NotificationResponse {
  id: string;
  type: NotificationType | string;
  priority?: NotificationPriority;
  title: string;
  message: string;
  metadata?: Record<string, any>;
  read: boolean;
  readAt?: string;
  actionUrl?: string;
  createdAt: string;
}

export interface NotificationListResponse {
  notifications: NotificationResponse[];
  total: number;
  page: number;
  pageSize: number;
}

// ============================================================================
// Audit Logs
// ============================================================================

export interface AuditLogResponse {
  id: string;
  userId: string;
  userName: string;
  organizationId: string;
  action: string;
  resourceType: string;
  resourceId: string;
  status: 'SUCCESS' | 'FAILURE';
  ipAddress: string;
  userAgent: string;
  metadata: Record<string, any>;
  createdAt: string;
}

export interface AuditLogListResponse {
  logs: AuditLogResponse[];
  total: number;
  page: number;
  pageSize: number;
}

export interface AuditLogFilterParams {
  userId?: string;
  action?: string | string[];
  status?: string | string[];
  resourceType?: string;
  resourceId?: string;
  startDate?: string;
  endDate?: string;
  page?: number;
  limit?: number;
}

// ============================================================================
// Webhooks
// ============================================================================

export type WebhookEvent =
  | 'booking.created'
  | 'booking.confirmed'
  | 'booking.cancelled'
  | 'shipment.departed'
  | 'shipment.arrived'
  | 'rate.updated';

export interface CreateWebhookRequest {
  url: string;
  events: WebhookEvent[];
  secret?: string;
  description?: string;
}

export interface UpdateWebhookRequest {
  url?: string;
  events?: WebhookEvent[];
  secret?: string;
  description?: string;
  isActive?: boolean;
}

export interface WebhookResponse {
  id: string;
  url: string;
  events: WebhookEvent[];
  isActive: boolean;
  description: string | null;
  createdAt: string;
  updatedAt: string;
}

// ============================================================================
// GDPR
// ============================================================================

export interface DeleteAccountRequest {
  confirmEmail: string;
  reason?: string;
}

export interface ConsentRequest {
  consentType: 'marketing' | 'analytics';
  granted: boolean;
}

export interface WithdrawConsentRequest {
  consentType: 'marketing' | 'analytics';
}

export interface ConsentStatus {
  marketing: boolean;
  analytics: boolean;
  updatedAt: string;
}

// ============================================================================
// Rates
// ============================================================================

export interface RateSearchRequest {
  origin: string;
  destination: string;
  containerType: string;
  mode: 'SEA' | 'AIR' | 'ROAD' | 'RAIL';
  departureDate: string;
  quantity: number;
  weight?: number;
  volume?: number;
  isHazmat?: boolean;
  imoClass?: string;
}

export interface RateSearchResponse {
  rates: RateQuote[];
  total: number;
  searchedAt: string;
}

export interface RateQuote {
  id: string;
  carrier: string;
  origin: string;
  destination: string;
  containerType: string;
  price: number;
  currency: string;
  transitDays: number;
  validUntil: string;
}

// ============================================================================
// CSV Rates (reuse existing types from rate-filters.ts if they exist)
// ============================================================================

export interface CsvRateSearchRequest {
  origin: string;
  destination: string;
  volumeCBM: number;
  weightKG: number;
  containerType?: string;
  hasDangerousGoods?: boolean;
  filters?: RateSearchFilters;
}

export interface RateSearchFilters {
  companies?: string[];
  onlyDirect?: boolean;
  excludeNonDgRoutes?: boolean;
  minPrice?: number;
  maxPrice?: number;
  currency?: 'USD' | 'EUR';
  minTransitDays?: number;
  maxTransitDays?: number;
  containerTypes?: string[];
  departureDate?: string;
  serviceLevels?: ('RAPID' | 'STANDARD' | 'ECONOMIC')[];
}

export type DgSurchargeStatus = 'computed' | 'on_request' | 'not_accepted';

export interface FobBreakdown {
  documentation: number;
  isps: number;
  handling: number;
  solas: number;
  customs: number;
  ams_aci: number;
  isf5: number;
  dgAdmin: number;
}

export interface PriceBreakdown {
  freightCharge: number;
  freightCurrency: string;
  fobFixed: number;
  fobHandling: number;
  fobDG: number;
  fobCurrency: string;
  fobBreakdown: FobBreakdown;
  dgSurchargeAmount: number | null;
  dgSurchargeCurrency: string;
  dgSurchargeStatus: DgSurchargeStatus;
  totalFreight: number;
  totalFob: number;
  totalPriceForSorting: number;
  primaryCurrency: string;
}

export interface CsvRateSearchResult {
  companyName: string;
  companyEmail: string;
  originCFS: string;
  origin: string;
  portOfLoading: string;
  routing: string;
  destinationCFS: string;
  destination: string;
  destinationCountry: string;
  containerType: string;
  priceBreakdown: PriceBreakdown;
  frequency: string;
  transitDays: number;
  validUntil: string;
  dgAccepted: boolean;
  dgSurchargeStatus: DgSurchargeStatus;
  remarks: string;
  source: string;
  matchScore: number;
  serviceLevel?: 'RAPID' | 'STANDARD' | 'ECONOMIC';
  priceMultiplier?: number;
  originalTransitDays?: number;
  adjustedTransitDays?: number;
}

/** @deprecated Use CsvRateSearchResult */
export type CsvRateResult = CsvRateSearchResult;

export interface CsvRateSearchResponse {
  results: CsvRateSearchResult[];
  totalResults: number;
  searchedFiles: string[];
  searchedAt: string;
  appliedFilters: RateSearchFilters;
}

export interface AvailableCompaniesResponse {
  companies: string[];
}

export interface FilterOptionsResponse {
  companies: string[];
  containerTypes: string[];
  currencies: string[];
}

// ============================================================================
// CSV Rates Admin
// ============================================================================

export interface CsvRateUploadRequest {
  companyName: string;
  file: File;
  type: 'STANDARD' | 'FOB_FRET';
}

export interface CsvRateUploadResponse {
  success: boolean;
  message: string;
  companyName: string;
  rowCount: number;
  uploadedAt: string;
}

export interface CsvRateConfigResponse {
  id: string;
  companyName: string;
  csvFilePath: string;
  type: 'STANDARD' | 'FOB_FRET';
  hasApi: boolean;
  apiConnector: string | null;
  isActive: boolean;
  uploadedAt: string;
  rowCount: number;
  metadata: Record<string, any>;
}

export interface CsvFileValidationResponse {
  valid: boolean;
  errors: string[];
  rowCount?: number;
}

// ============================================================================
// Dashboard (if exists)
// ============================================================================

export interface DashboardKPIs {
  totalBookings: number;
  activeShipments: number;
  pendingQuotes: number;
  totalRevenue: number;
}

// ============================================================================
// Common
// ============================================================================

export interface PaginationParams {
  page?: number;
  pageSize?: number;
  limit?: number;
}

export interface SuccessResponse {
  success: boolean;
  message?: string;
}
