"use server";

import { ClientsProps } from "@/types";
import { createClient } from "../lib/supabase/server";
import { cache } from "react";
import { headers } from "next/headers";
import { redirect } from "next/navigation";

export const checkUser = cache(async () => {
  const headersList = await headers();
  const userId = headersList.get("x-user-id");
  
  if (!userId) {
    redirect("/sign-in");
  }
  return userId;
});

export const getClients = cache(async (user_id?: string) => {
  const supabase = await createClient();
  let clients: ClientsProps[] | undefined = [];

  let clients_query = supabase
    .from("Client")
    .select(
      `client_id, client, role, created_on, site, gsc_domain_type_property, subscription:subscription (items_per_month, subscription_type)`,
    )
    .eq("auth_id", user_id)
    .not("client", "is", null)
    .order("role", { ascending: true })
    .order("client", { ascending: true });

  let all_clients_query = supabase
    .from("Client")
    .select(
      `client_id, client, role, created_on, site, gsc_domain_type_property, subscription:subscription (items_per_month, subscription_type)`,
    )
    .not("client", "is", null)
    .order("role", { ascending: true })
    .order("client", { ascending: true });

  if (user_id) {
    const { data, error } = await clients_query;
    if (error) return { status: 500, message: error.message };
    // @ts-ignore
    clients = data;
  } else {
    const { data, error } = await all_clients_query;
    if (error) return { status: 500, message: error.message };
    // @ts-ignore
    clients = data;
  }

  return { status: 200, clients: clients };
});

export const getApproved = cache(async (client_id: string | undefined) => {
  const supabase = await createClient();
  let { data, error } = await supabase
    .from("Approval")
    .select(`approved, last_modified`)
    .eq("client_id", client_id)
    .single();
  if (error) {
    return { status: 500, message: error.message };
  }
  return { status: 200, approved: data };
});
