import { redirect } from "@sveltejs/kit";
import type { PageServerLoad } from "./$types";
import { gql } from "graphql-request";
import { getGraphQLClient } from "$lib/api";

const USER_PROFILE_QUERY = gql`
  query UserProfile($id: String!) {
    userProfile(id: $id) {
      id
      first_name
      last_name
      email
      description
      avatar
      date_created
    }
    userGamification(userId: $id) {
      stats {
        user_id
        total_raw_points
        total_weighted_points
        recordings_count
        playbacks_count
        comments_count
        achievements_count
        rank
      }
      achievements {
        id
        code
        name
        description
        icon
        category
        date_unlocked
        progress
        required_count
      }
      recent_points {
        action
        points
        date_created
        recording_id
      }
    }
  }
`;

export const load: PageServerLoad = async ({ params, locals, fetch }) => {
  // Guard: Redirect to login if not authenticated
  if (!locals.authStatus.authenticated) {
    throw redirect(302, "/login");
  }

  const { id } = params;

  try {
    const client = getGraphQLClient(fetch);
    const data = await client.request<{
      userProfile: {
        id: string;
        first_name: string | null;
        last_name: string | null;
        email: string;
        description: string | null;
        avatar: string | null;
        date_created: string;
      } | null;
      userGamification: {
        stats: {
          user_id: string;
          total_raw_points: number | null;
          total_weighted_points: number | null;
          recordings_count: number | null;
          playbacks_count: number | null;
          comments_count: number | null;
          achievements_count: number | null;
          rank: number;
        } | null;
        achievements: {
          id: string;
          code: string;
          name: string;
          description: string | null;
          icon: string | null;
          category: string | null;
          date_unlocked: string;
          progress: number | null;
          required_count: number;
        }[];
        recent_points: {
          action: string;
          points: number;
          date_created: string;
          recording_id: string | null;
        }[];
      } | null;
    }>(USER_PROFILE_QUERY, { id });

    if (!data.userProfile) {
      throw redirect(404, "/");
    }

    const gamification = data.userGamification;

    return {
      user: data.userProfile,
      stats: {
        comments_count: gamification?.stats?.comments_count || 0,
        likes_count: 0,
      },
      gamification,
      isOwnProfile: locals.authStatus.user?.id === id,
    };
  } catch (error) {
    console.error("Failed to load user profile:", error);
    throw redirect(404, "/");
  }
};
