package adminfinance

import (
	"context"

	"hfb_sys/backend/internal/timeutil"
)

func (r *Repository) Dashboard(ctx context.Context, query DashboardQuery) (*DashboardDTO, error) {
	dailyItems, err := r.dailyItems(ctx, query)
	if err != nil {
		return nil, err
	}
	summary, err := r.summary(ctx, query)
	if err != nil {
		return nil, err
	}
	return &DashboardDTO{
		Summary:     *summary,
		DailyItems:  dailyItems,
		GeneratedAt: timeutil.ShanghaiNow(),
	}, nil
}

func (r *Repository) summary(ctx context.Context, query DashboardQuery) (*FinanceSummaryDTO, error) {
	db := r.db.WithContext(ctx)
	var payment paymentSummaryRow
	if err := db.Table("payment_orders").
		Select(`COALESCE(SUM(CASE WHEN biz_type IN ('order_pay') AND status = 'paid' THEN amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunded' THEN amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunding' THEN amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent,
			COALESCE(SUM(CASE WHEN biz_type IN ('order_pay') AND status = 'paid' THEN 1 ELSE 0 END), 0) AS successful_pay_count,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunded' THEN 1 ELSE 0 END), 0) AS successful_refund_count,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count`,
			refundBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes()).
		Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
		Scan(&payment).Error; err != nil {
		return nil, err
	}

	var settlement settlementSummaryRow
	if err := db.Table("rental_orders AS ro").
		Select(`COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
				COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent,
				COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent,
				COUNT(ro.id) AS settled_order_count`).
		Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'").
		Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(db)).
		Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
		Scan(&settlement).Error; err != nil {
		return nil, err
	}

	var exceptionCount int64
	if err := db.Table("(?) AS d", r.financeDetailBaseQuery(ctx, DetailQuery{
		DateType:  "settled",
		StartDate: query.StartDate,
		EndDate:   query.EndDate,
	})).
		Where("finance_status <> ?", "normal").
		Count(&exceptionCount).Error; err != nil {
		return nil, err
	}

	return &FinanceSummaryDTO{
		TotalFlowAmountCent:         payment.TotalFlowAmountCent,
		TotalRefundAmountCent:       payment.TotalRefundAmountCent,
		PendingRefundAmountCent:     payment.PendingRefundAmountCent,
		ChannelNetAmountCent:        payment.TotalFlowAmountCent - payment.TotalRefundAmountCent,
		PlatformIncomeAmountCent:    settlement.PlatformIncomeAmountCent,
		OwnerShouldIncomeAmountCent: settlement.OwnerShouldIncomeAmountCent,
		OwnerWalletIncomeAmountCent: settlement.OwnerWalletIncomeAmountCent,
		SettlementDiffAmountCent:    settlement.OwnerShouldIncomeAmountCent - settlement.OwnerWalletIncomeAmountCent,
		SuccessfulPayCount:          payment.SuccessfulPayCount,
		SuccessfulRefundCount:       payment.SuccessfulRefundCount,
		PendingRefundCount:          payment.PendingRefundCount,
		SettledOrderCount:           settlement.SettledOrderCount,
		FinancialExceptionCount:     exceptionCount,
	}, nil
}

func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) ([]FinanceDailyDTO, error) {
	db := r.db.WithContext(ctx)
	payments := make([]dailyPaymentRow, 0)
	if err := db.Table("payment_orders").
		Select(`DATE(created_at) AS date,
			COALESCE(SUM(CASE WHEN biz_type IN ('order_pay') AND status = 'paid' THEN amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunded' THEN amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunding' THEN amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent,
			COALESCE(SUM(CASE WHEN biz_type IN ('order_pay') AND status = 'paid' THEN 1 ELSE 0 END), 0) AS successful_pay_count,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunded' THEN 1 ELSE 0 END), 0) AS successful_refund_count,
			COALESCE(SUM(CASE WHEN biz_type IN ? AND status = 'refunding' THEN 1 ELSE 0 END), 0) AS pending_refund_count`,
			refundBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes()).
		Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
		Group("DATE(created_at)").
		Scan(&payments).Error; err != nil {
		return nil, err
	}

	settlements := make([]dailySettlementRow, 0)
	if err := db.Table("rental_orders AS ro").
		Select(`DATE(ro.settled_at) AS date,
				COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
				COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent,
				COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent,
				COUNT(ro.id) AS settled_order_count`).
		Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'").
		Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(db)).
		Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
		Group("DATE(ro.settled_at)").
		Scan(&settlements).Error; err != nil {
		return nil, err
	}

	itemsByDate := make(map[string]FinanceDailyDTO)
	for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) {
		date := day.Format("2006-01-02")
		itemsByDate[date] = FinanceDailyDTO{Date: date}
	}
	for _, row := range payments {
		item := itemsByDate[row.Date]
		item.Date = row.Date
		item.TotalFlowAmountCent = row.TotalFlowAmountCent
		item.TotalRefundAmountCent = row.TotalRefundAmountCent
		item.PendingRefundAmountCent = row.PendingRefundAmountCent
		item.ChannelNetAmountCent = row.TotalFlowAmountCent - row.TotalRefundAmountCent
		item.SuccessfulPayCount = row.SuccessfulPayCount
		item.SuccessfulRefundCount = row.SuccessfulRefundCount
		item.PendingRefundCount = row.PendingRefundCount
		itemsByDate[row.Date] = item
	}
	for _, row := range settlements {
		item := itemsByDate[row.Date]
		item.Date = row.Date
		item.PlatformIncomeAmountCent = row.PlatformIncomeAmountCent
		item.OwnerShouldIncomeAmountCent = row.OwnerShouldIncomeAmountCent
		item.OwnerWalletIncomeAmountCent = row.OwnerWalletIncomeAmountCent
		item.SettlementDiffAmountCent = row.OwnerShouldIncomeAmountCent - row.OwnerWalletIncomeAmountCent
		item.SettledOrderCount = row.SettledOrderCount
		itemsByDate[row.Date] = item
	}

	items := make([]FinanceDailyDTO, 0, len(itemsByDate))
	for day := dayStart(query.StartDate); !day.After(query.EndDate); day = day.AddDate(0, 0, 1) {
		items = append(items, itemsByDate[day.Format("2006-01-02")])
	}
	return items, nil
}

type paymentSummaryRow struct {
	TotalFlowAmountCent     int64
	TotalRefundAmountCent   int64
	PendingRefundAmountCent int64
	SuccessfulPayCount      int64
	SuccessfulRefundCount   int64
	PendingRefundCount      int64
}

type settlementSummaryRow struct {
	PlatformIncomeAmountCent    int64
	OwnerShouldIncomeAmountCent int64
	OwnerWalletIncomeAmountCent int64
	SettledOrderCount           int64
}

type dailyPaymentRow struct {
	Date                    string
	TotalFlowAmountCent     int64
	TotalRefundAmountCent   int64
	PendingRefundAmountCent int64
	SuccessfulPayCount      int64
	SuccessfulRefundCount   int64
	PendingRefundCount      int64
}

type dailySettlementRow struct {
	Date                        string
	PlatformIncomeAmountCent    int64
	OwnerShouldIncomeAmountCent int64
	OwnerWalletIncomeAmountCent int64
	SettledOrderCount           int64
}
