import { hasPermission, createGuestSession } from "../db";
import { getUser, setSessionCookie, getClientInfo } from "../auth";
import { config } from "../config";

type User = ReturnType<typeof getUser>;

// Helper to get or create guest session
export function getOrCreateUser(req: Request, server: any): { user: User, headers?: Headers } {
  let user = getUser(req, server);
  if (user) return { user };

  if (config.allowGuests) {
    const { userAgent, ipAddress } = getClientInfo(req, server);
    const guest = createGuestSession(userAgent, ipAddress);
    console.log(`[AUTH] Guest session created: user="${guest.user.username}" id=${guest.user.id} ip=${ipAddress}`);
    const headers = new Headers();
    headers.set("Set-Cookie", setSessionCookie(guest.token));
    return { user: guest.user, headers };
  }

  return { user: null };
}

// Check if user has permission (including default permissions)
export function userHasPermission(user: User, resourceType: string, resourceId: string | null, permission: string): boolean {
  if (!user) return false;
  if (user.is_admin) return true;

  // Guests can never control playback
  if (user.is_guest && permission === "control") return false;

  // Check default permissions from config
  if (resourceType === "channel" && config.defaultPermissions?.includes(permission)) {
    return true;
  }

  // Check user-specific permissions
  return hasPermission(user.id, resourceType, resourceId, permission);
}
