import { Platform } from "react-native";
import apiClient from "./apiClient";
import type { ApiEnvelope, LoginData, MobileUser, RefreshData } from "../types/auth";

function buildDevicePayload() {
  return {
    device_id: `mobile-${Platform.OS}`,
    device_name: Platform.OS,
    platform: Platform.OS,
  };
}

export async function login(email: string, password: string): Promise<LoginData> {
  const response = await apiClient.post<ApiEnvelope<LoginData>>(
    "/login.php",
    {
      email,
      password,
      ...buildDevicePayload(),
    },
    {
      headers: {
        "X-Skip-Auth": "1",
        "X-Skip-Refresh": "1",
      },
    }
  );

  if (!response.data?.success || !response.data.data) {
    throw new Error(response.data?.message || "Login failed");
  }

  return response.data.data;
}

export async function me(): Promise<MobileUser> {
  const response = await apiClient.get<ApiEnvelope<{ user: MobileUser }>>("/me.php");

  if (!response.data?.success || !response.data.data?.user) {
    throw new Error(response.data?.message || "Invalid session");
  }

  return response.data.data.user;
}

export async function refresh(refreshToken: string): Promise<RefreshData> {
  const response = await apiClient.post<ApiEnvelope<RefreshData>>(
    "/refresh.php",
    {
      refresh_token: refreshToken,
      ...buildDevicePayload(),
    },
    {
      headers: {
        "X-Skip-Auth": "1",
        "X-Skip-Refresh": "1",
      },
    }
  );

  if (!response.data?.success || !response.data.data) {
    throw new Error(response.data?.message || "Refresh failed");
  }

  return response.data.data;
}

export async function logout(refreshToken: string): Promise<void> {
  await apiClient.post<ApiEnvelope<null>>(
    "/logout.php",
    {
      refresh_token: refreshToken,
    },
    {
      headers: {
        "X-Skip-Auth": "1",
        "X-Skip-Refresh": "1",
      },
    }
  );
}
