import { getDeviceInfo } from "@/utils/deviceInfo";
import { createCoreAPIClient, createRawCoreAPIClient } from "../coreClient";
import { getSessionOptions } from "@/lib/cookies";

export interface SigninPayload {
  email: string;
  password: string;
}

const coreClient = createCoreAPIClient();

export async function adminSignin(payload: SigninPayload) {
  const { email, password } = payload;
  try {
    const deviceInfo = await getDeviceInfo();
    const response = await coreClient(
      "/v2/admin/console-user/signin",
      {
        method: "POST",
        body: JSON.stringify({
          email,
          password,
          fcmToken: deviceInfo.fcmToken,
          ipAddress: deviceInfo.ipAddress,
          deviceType: deviceInfo.deviceType,
          os: deviceInfo.os,
          browser: deviceInfo.browser,
          location: deviceInfo.location,
        }),
      },
      true,
    );

    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed Signin. Please try again.",
      data: null,
      success: false,
    };
  }
}

/**
 * Redeems a one-time sign-in token from an email link.
 *
 * Uses the raw client deliberately. `createCoreAPIClient` treats a 401 as an
 * expired session — it tries to rotate, then throws a redirect to `/auth/logout` —
 * which is the wrong response here: a 401 means *this token* is spent, and the
 * caller may well have a perfectly good session already that logging out would
 * destroy. The raw response also carries the `Set-Cookie` headers the caller has
 * to forward.
 */
export async function ssoSignin(token: string, request?: Request) {
  const rawClient = createRawCoreAPIClient();
  try {
    /*
     * Device details come off the request rather than being looked up.
     *
     * `ipAddress` is always supplied — "unknown" if the proxy didn't say — because
     * an absent value sends getDeviceInfo to an external IP service, and this call
     * sits directly between someone clicking a link and their page loading.
     */
    const deviceInfo = await getDeviceInfo({
      userAgent: request?.headers.get("user-agent") ?? null,
      ipAddress:
        request?.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
        "unknown",
      location: "Signed in from an email link",
    });
    return await rawClient("/v2/admin/console-user/sso-signin", {
      method: "POST",
      body: JSON.stringify({
        token,
        fcmToken: deviceInfo.fcmToken,
        ipAddress: deviceInfo.ipAddress,
        deviceType: deviceInfo.deviceType,
        os: deviceInfo.os,
        browser: deviceInfo.browser,
        location: deviceInfo.location,
      }),
    });
  } catch (error) {
    console.error("SSO sign-in failed:", error);
    return null;
  }
}

export async function adminSignout(request: Request) {
  try {
    const options = getSessionOptions(request);
    const response = await coreClient(
      "/v2/admin/console-user/session-revoke",
      {
        method: "DELETE",
        headers: {
          ...options,
        },
      },
      true,
    );
    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed Signout. Please try again.",
      data: null,
      success: false,
    };
  }
}

export async function adminRotateSession(request: Request) {
  try {
    const deviceInfo = await getDeviceInfo();
    const options = getSessionOptions(request);
    const response = await coreClient(
      "/v2/admin/console-user/session-rotate",
      {
        method: "PATCH",
        body: JSON.stringify({
          fcmToken: deviceInfo.fcmToken,
          ipAddress: deviceInfo.ipAddress,
          deviceType: deviceInfo.deviceType,
          os: deviceInfo.os,
          browser: deviceInfo.browser,
          location: deviceInfo.location,
        }),
        headers: {
          ...options,
        },
      },
      true,
    );
    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed to rotate session.",
      data: null,
      success: false,
    };
  }
}

export async function checkSuperAdminExists() {
  try {
    const response = await coreClient<{ exists: boolean }>(
      "/v2/admin/console-user/check-super-admin",
      { method: "GET" },
      false,
    );
    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed to check super admin.",
      data: { exists: true }, // Default to true to prevent accidental setup access
      success: false,
    };
  }
}

export async function createInitialSuperAdmin(
  payload: SigninPayload & {
    firstName: string;
    lastName: string;
    username: string;
  },
) {
  try {
    const response = await coreClient(
      "/v2/admin/console-user/super-admin",
      {
        method: "POST",
        body: JSON.stringify(payload),
      },
      false,
    );
    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed to create super admin.",
      data: null,
      success: false,
    };
  }
}
export async function setPassword(payload: {
  token: string;
  password: string;
}) {
  try {
    const response = await coreClient(
      "/v2/admin/console-user/set-password",
      {
        method: "POST",
        body: JSON.stringify(payload),
      },
      false,
    );
    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed to set password.",
      data: null,
      success: false,
    };
  }
}

export async function requestPasswordReset(email: string) {
  try {
    const response = await coreClient(
      "/v2/admin/console-user/request-password-reset",
      {
        method: "POST",
        body: JSON.stringify({ email }),
      },
      false,
    );
    return response;
  } catch (error) {
    return {
      message: (error as Error).message ?? "Failed to request password reset.",
      data: null,
      success: false,
    };
  }
}
