import axios from "axios";
import type { LoginPayload, LoginResponse, AdminProfile, ResetPasswordPayload } from "@/domain/entities/auth";
import type { AuthRepository } from "@/domain/repositories/auth.repository";
import { api, apiClient } from "@/infrastructure/api/api-client";
import { tokenStorage } from "@/infrastructure/auth/token-storage";
import { env } from "@/infrastructure/config/env";

/**
 * Password reset/forgot live on the shared fleet auth route (`/api/v1/fleet/auth`),
 * not under `/api/admin`, and are public (no auth header). We call them with a bare
 * axios instance so the admin baseURL and bearer-token interceptor don't apply.
 */
const FLEET_AUTH_BASE = `${env.backendOrigin}/api/v1/fleet/auth`;

export class AuthRepositoryImpl implements AuthRepository {
  async login(payload: LoginPayload): Promise<LoginResponse> {
    // Login returns the full envelope (status/message/token) — read directly, do not unwrap.
    const { data } = await apiClient.post<LoginResponse>("/auth/login", payload);
    if (data.status && data.data?.token) {
      tokenStorage.set(data.data.token);
    }
    return data;
  }

  async logout(): Promise<void> {
    try {
      await apiClient.post("/auth/logout");
    } finally {
      tokenStorage.clear();
    }
  }

  getMe() {
    return api.get<AdminProfile>("/auth/me");
  }

  async forgotPassword(email: string): Promise<void> {
    await axios.post(`${FLEET_AUTH_BASE}/password/forgot`, { email });
  }

  async resetPassword(payload: ResetPasswordPayload): Promise<void> {
    await axios.post(`${FLEET_AUTH_BASE}/password/reset`, payload);
  }
}
