import { apiClient, getDataOrThrow } from "@/lib/api";
import { getNullableData } from "@/lib/api/response-helpers";
import {
  userSchema,
  addressSchema,
  type UserProfile,
  type Address,
} from "@customer-portal/domain/customer";
import {
  updateCustomerProfileRequestSchema,
  type UpdateCustomerProfileRequest,
} from "@customer-portal/domain/auth";

export const accountService = {
  async getProfile() {
    const response = await apiClient.GET<UserProfile>("/api/me");
    const data = getNullableData<UserProfile>(response);
    if (!data) {
      return null;
    }
    return userSchema.parse(data);
  },

  async updateProfile(update: UpdateCustomerProfileRequest) {
    const sanitized = updateCustomerProfileRequestSchema.parse(update);
    const response = await apiClient.PATCH<UserProfile>("/api/me", { body: sanitized });
    const data = getDataOrThrow<UserProfile>(response, "Failed to update profile");
    return userSchema.parse(data);
  },

  async getAddress() {
    const response = await apiClient.GET<Address>("/api/me/address");
    const data = getNullableData<Address>(response);
    if (!data) {
      return null;
    }
    return addressSchema.parse(data);
  },

  async updateAddress(address: Address) {
    const response = await apiClient.PATCH<Address>("/api/me/address", { body: address });
    const data = getDataOrThrow<Address>(response, "Failed to update address");
    return addressSchema.parse(data);
  },
};
