import axios from 'axios';

import { OrderTableQuery } from '../request/GetOrderTableRequest';
import { OrderResponse } from '../response/OrderResponse';

axios.interceptors.response.use(response => {
   return response;
}, async error => {
  if (error.response?.status === 401) {
    const resp = await axios.get(process.env.NEXT_PUBLIC_API_URL + "/auth/login", {withCredentials: true})
    window.location.href = resp.data.Location
  }
  return error
})
export const CreateOrder = async (orderer: string, dateDue: string): Promise<OrderResponse> => {
	const queryParams = new URLSearchParams({
		orderer: orderer,
		date_due: dateDue,
		date_placed: new Date().toISOString()
	})
	const res = await axios.post(process.env.NEXT_PUBLIC_API_URL + `/order/create?${queryParams.toString()}`, {}, {withCredentials: true})
	return res.data as OrderResponse
}

export const GetOrderById = async (orderId: number): Promise<OrderResponse> => {
	const queryParams = new URLSearchParams({
		order_id: orderId.toString()
	})
	const res = await axios.get(process.env.API_URL + `/order?${queryParams.toString()}`)
	return res.data as OrderResponse
}

export const GetOrderTable = async (page: number, filter: number, searchParams: OrderTableQuery): Promise<OrderResponse[]> => {
	const queryParams = new URLSearchParams({
		page: page.toString(),
		filter: filter.toString()
	})

	console.log(page)
	console.log(filter)
	console.log(searchParams)
	console.log(queryParams.toString())
	const res = await axios.put(process.env.NEXT_PUBLIC_API_URL + `/order/table?${queryParams.toString()}`, searchParams, {withCredentials: true})
	if(res.data?.Location) {
		window.location.href = res.data.Location
	}
	return res.data || []
}

export const DeleteOrder = async (orderId: number) => {
	const queryParams = new URLSearchParams({
		order_id: orderId.toString()
	})

	await axios.delete(process.env.API_URL + `/order?${queryParams}`)
}
