import axios from 'axios';
import { cookies } from 'next/headers';

const $api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_HOST || 'https://back.v1techprod.ru',
});

$api.interceptors.request.use(function (req) {
  const cookieStore = cookies();
  const JSESSIONID = cookieStore.get('JSESSIONID')?.value;

  req.headers.set('JSESSIONID', JSESSIONID);
  req.headers.set('Jsessionid', JSESSIONID);

  return req;
});

$api.interceptors.response.use(
  function (response) {
    const responseData = response.data as { message: string; result: number; key?: string };
    if (responseData?.result === 2 || responseData.key === 'errLogin_Session') {
      throw {
        status: 401,
        message: 'UnAuthorized',
      };
    }
    return response;
  },
  function (error) {
    throw error;
  },
);

export async function GET(req: Request, ctx: any) {
  const params = new URLSearchParams(req.url.split('?')[1]);

  const res = await $api
    .get(ctx.params.path.join('/'), {
      params: params,
    })
    .then((res) =>  Response.json(res.data))
    .catch((err) => {
        return Response.json({
            message: err.message,
        }, {
            status: err.status
        })
    })
  return res;
}

export async function POST(req: Request, ctx: any) {
  const params = new URLSearchParams(req.url.split('?')[1]);

  const res = await $api
    .post(ctx.params.path.join('/'), req.body, {
      params: params,
    })
    .then((res) =>  Response.json(res.data))
    .catch((err) => {
        return Response.json({
            message: err.message,
        }, {
            status: err.status
        })
    });

    
  return res;
}
