package com.example.petstoremobile.viewmodels;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;

import com.example.petstoremobile.dtos.CustomerDTO;
import com.example.petstoremobile.repositories.CustomerRepository;
import com.example.petstoremobile.utils.Resource;

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class CustomerDetailViewModel extends ViewModel {
    private final CustomerRepository repository;

    private long customerId = -1;
    private boolean isEditing = false;

    @Inject
    public CustomerDetailViewModel(CustomerRepository repository) {
        this.repository = repository;
    }

    public void setCustomerId(long id, boolean isEditing) {
        this.customerId = id;
        this.isEditing = isEditing;
    }

    public long getCustomerId() { return customerId; }
    public boolean isEditing() { return isEditing; }

    public CustomerDTO createCustomerDto(String username, String password, String firstName,
                                        String lastName, String email, String phone,
                                        boolean active, Integer loyaltyPoints) {
        CustomerDTO dto = new CustomerDTO(username, password, firstName, lastName, email, phone);
        dto.setFullName(firstName + " " + lastName);
        dto.setActive(active);
        dto.setRole("CUSTOMER");
        if (isEditing && loyaltyPoints != null) {
            dto.setLoyaltyPoints(loyaltyPoints);
        }
        return dto;
    }

    public LiveData<Resource<CustomerDTO>> loadCustomer(long id) {
        return repository.getCustomerById(id);
    }

    public LiveData<Resource<CustomerDTO>> saveCustomer(CustomerDTO dto) {
        if (isEditing && customerId > 0) {
            return repository.updateCustomer(customerId, dto);
        } else {
            return repository.createCustomer(dto);
        }
    }

    public LiveData<Resource<Void>> deleteCustomer() {
        return repository.deleteCustomer(customerId);
    }
}
