import { cookies } from "next/headers";
import type { NextResponse } from "next/server";
import type { StorefrontAccountSession } from "@/types/storefront";

export const STOREFRONT_ACCOUNT_COOKIE = "shop_starter_account";

function normalizeSession(
  value: Partial<StorefrontAccountSession> | null | undefined,
): StorefrontAccountSession | null {
  if (!value || typeof value !== "object") {
    return null;
  }

  const email = typeof value.email === "string" ? value.email.trim() : "";
  const firstName = typeof value.firstName === "string" ? value.firstName.trim() : "";
  const lastName = typeof value.lastName === "string" ? value.lastName.trim() : "";
  const accountType = value.accountType === "company" ? "company" : value.accountType === "person" ? "person" : null;

  if (!email || !firstName || !lastName || !accountType) {
    return null;
  }

  return {
    email,
    firstName,
    lastName,
    phone: typeof value.phone === "string" ? value.phone.trim() || undefined : undefined,
    address1: typeof value.address1 === "string" ? value.address1.trim() || undefined : undefined,
    postcode: typeof value.postcode === "string" ? value.postcode.trim() || undefined : undefined,
    city: typeof value.city === "string" ? value.city.trim() || undefined : undefined,
    companyName:
      typeof value.companyName === "string" ? value.companyName.trim() || undefined : undefined,
    oib: typeof value.oib === "string" ? value.oib.trim() || undefined : undefined,
    companyAddress:
      typeof value.companyAddress === "string"
        ? value.companyAddress.trim() || undefined
        : undefined,
    accountType,
  };
}

export async function getAccountSessionFromCookies() {
  const cookieStore = await cookies();
  const rawValue = cookieStore.get(STOREFRONT_ACCOUNT_COOKIE)?.value;

  if (!rawValue) {
    return null;
  }

  try {
    const parsed = JSON.parse(rawValue) as Partial<StorefrontAccountSession>;
    return normalizeSession(parsed);
  } catch {
    return null;
  }
}

export function applyAccountSessionCookie(
  response: NextResponse,
  session: StorefrontAccountSession | null,
) {
  if (!session) {
    response.cookies.delete(STOREFRONT_ACCOUNT_COOKIE);
    return;
  }

  response.cookies.set(STOREFRONT_ACCOUNT_COOKIE, JSON.stringify(session), {
    path: "/",
    sameSite: "lax",
    httpOnly: false,
    maxAge: 60 * 60 * 24 * 30,
  });
}

export function buildAccountSession(
  input: Partial<StorefrontAccountSession>,
): StorefrontAccountSession | null {
  return normalizeSession(input);
}
