import { serverSupabaseClient } from "../../utils/useSupabase";
import { getProfile } from "../../db/profile";

export default defineEventHandler(async (event) => {
  const { username, password } = await readBody(event);

  if (!username || !password) {
    throw createError({
      statusCode: 400,
      message: "username und password erforderlich",
    });
  }

  const email = `${username.toLowerCase()}@rebreak.internal`;
  const supabase = serverSupabaseClient(event);

  const { data, error } = await supabase.auth.signInWithPassword({
    email,
    password,
  });
  if (error) throw createError({ statusCode: 401, message: error.message });

  const dbProfile = await getProfile(data.user.id);

  return {
    session: {
      access_token: data.session.access_token,
      refresh_token: data.session.refresh_token,
      expires_at: data.session.expires_at,
    },
    profile: {
      id: data.user.id,
      email: data.user.email ?? "",
      username: dbProfile?.username ?? "",
      nickname: dbProfile?.nickname ?? null,
      avatar: dbProfile?.avatar ?? null,
      plan: (dbProfile?.plan === "premium"
        ? "legend"
        : dbProfile?.plan === "standard"
          ? "pro"
          : dbProfile?.plan ?? "free") as "free" | "pro" | "legend",
      streak: dbProfile?.streak ?? 0,
      created_at: dbProfile?.createdAt?.toISOString() ?? data.user.created_at,
    },
  };
});
