"use client"

import { CrudShowResponse, ExpensesClient } from "@garage/api"
import { createContext, useContext } from "react"

type BaseExpenseContextValue = NonNullable<CrudShowResponse<ExpensesClient>["data"]>

type ExpenseNamedRelation = {
    id?: number
    name?: string | null
    title?: string | null
}

type ExpenseVendorRelation = ExpenseNamedRelation & {
    company_name?: string | null
    first_name?: string | null
    last_name?: string | null
}

type ExpenseJobCardRelation = {
    id?: number
    order_number?: string | null
    estimate_number?: string | null
    title?: string | null
}

type ExpenseTaxRelation = ExpenseNamedRelation & {
    rate?: string | number | null
}

type ExpenseLabel = {
    id?: number
    title?: string | null
    color_code?: string | null
}

export type ExpenseContextValue = BaseExpenseContextValue & {
    discount?: string | null
    discount_amount_major?: number | null
    vendor?: ExpenseVendorRelation | null
    department?: ExpenseNamedRelation | null
    category?: ExpenseNamedRelation | null
    job_card?: ExpenseJobCardRelation | null
    tax?: ExpenseTaxRelation | null
    labels?: ExpenseLabel[] | null
}
 

const ExpenseContext = createContext<ExpenseContextValue | null>(null)

export function ExpenseProvider({
    expense,
    children,
}: {
    expense: ExpenseContextValue
    children: React.ReactNode
}) {
    return (
        <ExpenseContext.Provider value={expense}>
            {children}
        </ExpenseContext.Provider>
    )
}

export function useExpense() {
    return useContext(ExpenseContext)
}
