'use client'
import { pb } from './pocketbase'
import type { PBUser } from '@/types'

const COOKIE_TOKEN = 'pb_token'
const COOKIE_ROLE = 'pb_role'
const COOKIE_MAX_AGE = 60 * 60 * 24 * 14 // 14 days

export function getAuthUser(): PBUser | null {
  if (!pb.authStore.isValid) return null
  return pb.authStore.model as PBUser | null
}

export function syncAuthCookies(): void {
  if (pb.authStore.isValid && pb.authStore.token) {
    const user = pb.authStore.model as PBUser | null
    const role = user?.role ?? ''
    document.cookie = `${COOKIE_TOKEN}=${pb.authStore.token}; path=/; max-age=${COOKIE_MAX_AGE}; SameSite=Lax`
    document.cookie = `${COOKIE_ROLE}=${role}; path=/; max-age=${COOKIE_MAX_AGE}; SameSite=Lax`
  } else {
    clearAuthCookies()
  }
}

export function clearAuthCookies(): void {
  document.cookie = `${COOKIE_TOKEN}=; path=/; max-age=0`
  document.cookie = `${COOKIE_ROLE}=; path=/; max-age=0`
}

export function logout(): void {
  pb.authStore.clear()
  clearAuthCookies()
  window.location.href = '/auth'
}
