package com.example.demo.dashboard;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;

@Repository
public class DashboardRepository {

    @PersistenceContext
    private EntityManager entityManager;

    public BigDecimal sumTodaySalesOrders(Long shopId) {
        Object result = entityManager.createNativeQuery(
                "SELECT COALESCE(SUM(amount), 0) FROM sales_orders " +
                "WHERE shop_id = :shopId AND status = 'approved' AND DATE(order_time) = CURRENT_DATE()"
        ).setParameter("shopId", shopId).getSingleResult();
        return toBigDecimal(result);
    }

    public BigDecimal sumMonthGrossProfitApprox(Long shopId) {
        Object result = entityManager.createNativeQuery(
                "SELECT COALESCE(SUM(soi.amount - soi.quantity * COALESCE(pp.purchase_price, 0)), 0) AS gp " +
                "FROM sales_orders so " +
                "JOIN sales_order_items soi ON soi.order_id = so.id " +
                "LEFT JOIN product_prices pp ON pp.product_id = soi.product_id AND pp.shop_id = so.shop_id " +
                "WHERE so.shop_id = :shopId AND so.status = 'approved' " +
                "AND so.order_time >= DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01') " +
                "AND so.order_time < DATE_ADD(DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01'), INTERVAL 1 MONTH)"
        ).setParameter("shopId", shopId).getSingleResult();
        return toBigDecimal(result);
    }

    public BigDecimal sumMonthSalesOrders(Long shopId) {
        Object result = entityManager.createNativeQuery(
                "SELECT COALESCE(SUM(amount), 0) FROM sales_orders " +
                "WHERE shop_id = :shopId AND status = 'approved' " +
                "AND order_time >= DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01') " +
                "AND order_time < DATE_ADD(DATE_FORMAT(CURRENT_DATE(), '%Y-%m-01'), INTERVAL 1 MONTH)"
        ).setParameter("shopId", shopId).getSingleResult();
        return toBigDecimal(result);
    }

    public BigDecimal sumTotalInventoryQty(Long shopId) {
        Object result = entityManager.createNativeQuery(
                "SELECT COALESCE(SUM(quantity), 0) FROM inventories WHERE shop_id = :shopId"
        ).setParameter("shopId", shopId).getSingleResult();
        return toBigDecimal(result);
    }

    private BigDecimal toBigDecimal(Object value) {
        if (value == null) return BigDecimal.ZERO;
        if (value instanceof BigDecimal) return (BigDecimal) value;
        if (value instanceof Number) return BigDecimal.valueOf(((Number) value).doubleValue());
        try {
            return new BigDecimal(value.toString());
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }

    public Long findShopIdByUserId(Long userId) {
        if (userId == null) return null;
        Object result = entityManager.createNativeQuery(
                "SELECT shop_id FROM users WHERE id = :userId LIMIT 1"
        ).setParameter("userId", userId).getSingleResult();
        if (result == null) return null;
        if (result instanceof Number) return ((Number) result).longValue();
        try {
            return Long.valueOf(result.toString());
        } catch (Exception e) {
            return null;
        }
    }
}



