// src/lib/auth-utils.ts
import { prisma } from "@/lib/prisma";

export async function getFreshAccessToken(userId: string) {
  // 1. Find the account in PostgreSQL
  const account = await prisma.account.findFirst({
    where: { userId },
  });

  if (!account || !account.refresh_token) {
    throw new Error("No refresh token available. User might need to re-login.");
  }

  // 2. Check if the token is expired (with a 1-minute buffer)
  const isExpired = (account.expires_at ?? 0) * 1000 < Date.now() + 60000;

  if (!isExpired && account.access_token) {
    return account.access_token;
  }

  // 3. If expired, request a new one from Microsoft
  console.log("🔄 Access token expired. Refreshing for user:", userId);
  
  try {
    const response = await fetch("https://login.microsoftonline.com/common/oauth2/v2.0/token", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        client_id: process.env.AUTH_MICROSOFT_ENTRA_ID_ID!,
        client_secret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET!,
        grant_type: "refresh_token",
        refresh_token: account.refresh_token,
        // CRITICAL: Re-declare scopes to ensure the new access_token has OneDrive permissions
        scope: "openid profile offline_access Files.ReadWrite Files.Read",
      }),
    });

    const tokens = await response.json();

    if (!response.ok) {
      console.error("❌ Microsoft Token Refresh Response Error:", tokens);
      throw tokens;
    }

    // 4. Update the Account table with the new tokens
    await prisma.account.update({
      where: { id: account.id },
      data: {
        access_token: tokens.access_token,
        expires_at: Math.floor(Date.now() / 1000 + tokens.expires_in),
        // Microsoft sometimes rotates the refresh_token; save it if they provide a new one
        refresh_token: tokens.refresh_token ?? account.refresh_token,
      },
    });

    return tokens.access_token;
  } catch (error) {
    console.error("❌ Failed to refresh Microsoft token:", error);
    // Returning a specific error string helps Auth.js or your components handle re-auth
    throw new Error("RefreshAccessTokenError");
  }
}