"use server";

import { Product, Price } from "@/types";
import pb from "@/lib/pocketbase";
import { getAuthCookie } from "@/app/(auth)/actions";

export async function apiPrices() {
  console.log('prices')
  try {
    const pocketbaseUrl = process.env.NEXT_PUBLIC_POCKETBASE_URL_STRING;
    if (!pocketbaseUrl) {
      throw Error('Connection Timeout');
    }
    const productRequest = await fetch(
      `${pocketbaseUrl}/api/collections/product/records?filter=(active=true)`,
      {
        cache: 'no-cache',
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    const productResponse = await productRequest.json();
    const unsortedProducts: Product[] = productResponse.items;
    const prices = await pb.collection("price").getFullList<Price>();
    for (const product of unsortedProducts) {
        product.metadata.benefits = JSON.parse(product.metadata.benefits as any);
        const pricesOfProduct = prices.filter(price => price.product_id === product.product_id);
        for (const priceOfProduct of pricesOfProduct){
            if (priceOfProduct.interval === "year"){
                product.yearlyPrice = priceOfProduct;
            } else {
                product.monthlyPrice = priceOfProduct;
            }
        }
    }
    
    const sortedProducts = unsortedProducts.sort((a: Product, b: Product) => a.product_order - b.product_order)
    return sortedProducts;
  } catch (error) {
    console.log(error);
    return [];
  }
}