import { api } from './client';
import type { ApiResponse, PaginatedResult, BaseFilters, QuoteStatus } from '../../types';

// Types
export interface Quote {
  id: string;
  tenant_id: string;
  quote_number: string;
  customer_id: string;
  customer_name: string;
  vehicle_id: string;
  vehicle_info: string;
  status: QuoteStatus;
  valid_until: string;
  labor_total: number;
  parts_total: number;
  discount_amount: number;
  tax: number;
  grand_total: number;
  notes: string | null;
  created_at: string;
  updated_at: string | null;
}

export interface QuoteItem {
  id: string;
  quote_id: string;
  item_type: 'service' | 'part';
  service_id: string | null;
  part_id: string | null;
  description: string;
  quantity: number;
  unit_price: number;
  discount: number;
  subtotal: number;
}

export interface CreateQuoteRequest {
  customer_id: string;
  vehicle_id: string;
  valid_days?: number;
  notes?: string;
}

export interface QuoteFilters extends BaseFilters {
  status?: QuoteStatus;
  customer_id?: string;
}

// API
export const quotesApi = {
  // List quotes with filters
  list: (filters?: QuoteFilters) =>
    api.get<ApiResponse<PaginatedResult<Quote>>>('/quotes', {
      params: filters,
    }),

  // Get single quote
  getById: (id: string) =>
    api.get<ApiResponse<Quote>>(`/quotes/${id}`),

  // Create new quote
  create: (data: CreateQuoteRequest) =>
    api.post<ApiResponse<Quote>>('/quotes', data),

  // Update quote
  update: (id: string, data: Partial<Quote>) =>
    api.patch<ApiResponse<Quote>>(`/quotes/${id}`, data),

  // Change status
  changeStatus: (id: string, status: QuoteStatus) =>
    api.post<ApiResponse<Quote>>(`/quotes/${id}/status`, { status }),

  // Get quote items
  getItems: (quoteId: string) =>
    api.get<ApiResponse<QuoteItem[]>>(`/quotes/${quoteId}/items`),

  // Add item to quote
  addItem: (quoteId: string, item: Partial<QuoteItem>) =>
    api.post<ApiResponse<QuoteItem>>(`/quotes/${quoteId}/items`, item),

  // Remove item from quote
  removeItem: (quoteId: string, itemId: string) =>
    api.delete<ApiResponse<null>>(`/quotes/${quoteId}/items/${itemId}`),

  // Convert to service order
  convertToOrder: (quoteId: string) =>
    api.post<ApiResponse<{ orderId: string }>>(`/quotes/${quoteId}/convert`),

  // Send to customer
  send: (quoteId: string, email?: string) =>
    api.post<ApiResponse<Quote>>(`/quotes/${quoteId}/send`, { email }),
};
