// pages/api/auth/[...auth0].js
import { handleAuth, handleLogin, handleCallback } from "@auth0/nextjs-auth0";
import executeQuery from "../../../services/db";

async function afterCallback(req, res, session, state) {
  // Get user login from database
  const res1 = await executeQuery({
    query: `SELECT * FROM Users WHERE email = ? AND ISNULL(date_canceled)`,
    values: [session.user.email],
  });

  const loginData = res1?.[0];

  // Find all accounts owned by the user
  // This is ACCOUNTS_AVAILABLE_QUERY from /services/auth.js
  const accountData = await executeQuery({
    query: `SELECT User_Accounts.type, COALESCE(User_Accounts.name, Orgs.name, Sales.name) as name,
    Orgs.id as org_id, Orgs.name as org_name, Rep.name as rep_name, Rep_User.email as rep_email,
    Orgs.max_licenses, Orgs.uuid, Orgs.assigned_licenses, Orgs.claimed_licenses, Orgs.sub_tenants, Orgs.replicators, Orgs.threat_detection, Orgs.parent_org, Orgs.onboarding_notifications,
    COALESCE(Sales.rate, Accounts.rate) as rate
    FROM User_Accounts
    LEFT JOIN Orgs ON Orgs.id = User_Accounts.id
    LEFT JOIN Accounts ON Accounts.id = Orgs.id
    LEFT JOIN Sales AS Rep ON Rep.id = Orgs.rep_id
    LEFT JOIN Users AS Rep_User ON Rep_User.id = Orgs.rep_id
    LEFT JOIN Sales ON Sales.id = User_Accounts.id
    WHERE User_Accounts.user_id = ? AND ISNULL(Orgs.date_canceled)`,
    values: [loginData?.id],
  });

  const managedAccountData = await executeQuery({
    query: `SELECT User_Accounts.type, COALESCE(User_Accounts.name, Orgs.name, Sales.name) as name,
    Orgs.id as org_id, Orgs.name as org_name, Rep.name as rep_name, Rep_User.email as rep_email,
    Orgs.max_licenses, Orgs.uuid, Orgs.assigned_licenses, Orgs.claimed_licenses, Orgs.sub_tenants, Orgs.replicators, Orgs.threat_detection, Orgs.parent_org, Orgs.onboarding_notifications,
    COALESCE(Sales.rate, Accounts.rate) as rate
    FROM Orgs
    LEFT JOIN User_Accounts ON (Orgs.id = User_Accounts.id AND User_Accounts.type = 'org')
    LEFT JOIN Accounts ON Accounts.id = Orgs.id
    LEFT JOIN Sales AS Rep ON Rep.id = Orgs.rep_id
    LEFT JOIN Users AS Rep_User ON Rep_User.id = Orgs.rep_id
    LEFT JOIN Sales ON Sales.id = User_Accounts.id
    WHERE Orgs.rep_id = ? AND ISNULL(Orgs.date_canceled)
    GROUP BY org_id`,
    values: [loginData?.id],
  });

  session.user.loginData = loginData;
  session.user.accounts = [...accountData, ...managedAccountData];
  return session;
}

export default handleAuth({
  async login(req, res) {
    try {
      // Pass custom parameters to login
      await handleLogin(req, res, {
        returnTo: "/dashboard",
      });
    } catch (error) {
      // Add your own custom error handling
      res.status(error.status || 400).end(error.message);
    }
  },
  async callback(req, res) {
    try {
      await handleCallback(req, res, { afterCallback });
    } catch (error) {
      res.status(error.status || 500).end(error.message);
    }
  },
});
