package org.example.petshopdesktop.api.endpoints;

import com.fasterxml.jackson.core.type.TypeReference;
import org.example.petshopdesktop.api.ApiClient;
import org.example.petshopdesktop.api.dto.common.PageResponse;
import org.example.petshopdesktop.api.dto.coupon.CouponRequest;
import org.example.petshopdesktop.api.dto.coupon.CouponResponse;

import java.util.List;

public class CouponApi {
    private static final CouponApi INSTANCE = new CouponApi();
    private final ApiClient apiClient;

    private CouponApi() {
        apiClient = ApiClient.getInstance();
    }

    public static CouponApi getInstance() {
        return INSTANCE;
    }

    public List<CouponResponse> listCoupons() throws Exception {
        String response = apiClient.getRawResponse("/api/v1/coupons?page=0&size=1000");
        PageResponse<CouponResponse> page = apiClient.getObjectMapper()
                .readValue(response, new TypeReference<PageResponse<CouponResponse>>() {});
        List<CouponResponse> content = page.getContent();
        return content != null ? content : java.util.Collections.emptyList();
    }

    public CouponResponse createCoupon(CouponRequest request) throws Exception {
        return apiClient.post("/api/v1/coupons", request, CouponResponse.class);
    }

    public CouponResponse updateCoupon(Long id, CouponRequest request) throws Exception {
        return apiClient.put("/api/v1/coupons/" + id, request, CouponResponse.class);
    }

    public void deleteCoupon(Long id) throws Exception {
        apiClient.delete("/api/v1/coupons/" + id);
    }

    public CouponResponse getCouponByCode(String code) throws Exception {
        return apiClient.get("/api/v1/coupons/code/" + code, CouponResponse.class);
    }
}
