package adminfinance

import (
	"context"

	"gorm.io/gorm"
)

func (r *Repository) Details(ctx context.Context, query DetailQuery) (*PaginatedResult, error) {
	// COUNT 只扫描 rental_orders 主表(过滤条件全部落在 ro.* 上,可命中
	// idx_rental_orders_settled_at_id / created_at_id 索引),不再套完整 5-JOIN
	// 子查询,避免大数据量翻页时 COUNT 拖慢。
	countDB := r.applyDetailFilters(r.db.WithContext(ctx).Table("rental_orders AS ro"), query)
	var total int64
	if err := countDB.Count(&total).Error; err != nil {
		return nil, err
	}
	if total == 0 {
		return &PaginatedResult{Items: []FinanceDetailDTO{}, Total: 0, Page: query.Page, PageSize: query.PageSize}, nil
	}

	// 明细行查询保留完整 JOIN,仅对当前分页命中的订单做金额聚合。
	db := r.financeDetailBaseQuery(ctx, query)
	offset := (query.Page - 1) * query.PageSize
	rows := make([]financeDetailRow, 0, query.PageSize)
	if err := db.Order("ro.id DESC").Offset(offset).Limit(query.PageSize).Scan(&rows).Error; err != nil {
		return nil, err
	}
	items := make([]FinanceDetailDTO, 0, len(rows))
	for _, row := range rows {
		items = append(items, row.toDTO())
	}
	return &PaginatedResult{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil
}

// applyDetailFilters 把仅依赖 rental_orders 主表字段的过滤条件挂到查询上,
// COUNT 与明细行查询共用,保证两者口径一致。
func (r *Repository) applyDetailFilters(db *gorm.DB, query DetailQuery) *gorm.DB {
	if query.OrderNo != "" {
		db = db.Where("ro.order_no = ?", query.OrderNo)
	}
	if query.UserID > 0 {
		db = db.Where("(ro.renter_id = ? OR ro.owner_id = ?)", query.UserID, query.UserID)
	}
	if query.OrderStatus != "" {
		db = db.Where("ro.status = ?", query.OrderStatus)
	}
	if query.SettlementStatus != "" {
		db = db.Where("ro.settlement_status = ?", query.SettlementStatus)
	}
	if !query.StartDate.IsZero() && !query.EndDate.IsZero() {
		if query.DateType == "created" {
			db = db.Where("ro.created_at >= ? AND ro.created_at <= ?", query.StartDate, query.EndDate)
		} else {
			db = db.Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate)
		}
	}
	return db
}

func (r *Repository) financeDetailBaseQuery(ctx context.Context, query DetailQuery) *gorm.DB {
	db := r.db.WithContext(ctx).Table("rental_orders AS ro").
		Select(`ro.id AS order_id, ro.order_no, ro.status AS order_status, ro.settlement_status, ro.refund_status,
			ro.renter_id, COALESCE(ru.phone, '') AS renter_phone, COALESCE(ru.nickname, '') AS renter_nickname,
			ro.owner_id, COALESCE(ou.phone, '') AS owner_phone, COALESCE(ou.nickname, '') AS owner_nickname,
				ro.rent_amount_cent AS order_rent_amount_cent, ro.deposit_amount_cent AS order_deposit_amount_cent,
				COALESCE(oc.rent_amount_cent, 0) AS checkout_rent_amount_cent,
				COALESCE(oc.renter_refund_amount_cent, 0) AS checkout_renter_refund_cent,
				COALESCE(oc.owner_income_amount_cent, 0) AS checkout_owner_income_cent,
				COALESCE(oc.platform_fee_cent, 0) AS checkout_platform_fee_cent,
				COALESCE(w.owner_wallet_income_amount_cent, 0) AS owner_wallet_income_amount_cent,
				COALESCE(p.paid_amount_cent, 0) AS paid_amount_cent,
				COALESCE(p.refunded_amount_cent, 0) AS refunded_amount_cent,
				COALESCE(p.refunding_amount_cent, 0) AS refunding_amount_cent,
				COALESCE(p.failed_refund_amount_cent, 0) AS failed_refund_amount_cent,
				COALESCE(p.paid_amount_cent, 0) - COALESCE(p.refunded_amount_cent, 0) AS channel_net_amount_cent,
				COALESCE(oc.platform_fee_cent, 0) + ((COALESCE(oc.owner_income_amount_cent, 0) - COALESCE(w.owner_wallet_income_amount_cent, 0))) AS platform_net_amount_cent,
				COALESCE(oc.owner_income_amount_cent, 0) - COALESCE(w.owner_wallet_income_amount_cent, 0) AS settlement_diff_amount_cent,
				CASE
					WHEN COALESCE(p.failed_refund_amount_cent, 0) > 0 THEN 'refund_failed'
					WHEN COALESCE(p.refunding_amount_cent, 0) > 0 OR ro.refund_status = 'refunding' THEN 'refund_pending'
					WHEN ABS(COALESCE(oc.owner_income_amount_cent, 0) - COALESCE(w.owner_wallet_income_amount_cent, 0)) >= ? THEN 'settlement_diff'
				ELSE 'normal'
			END AS finance_status,
			ro.created_at, ro.settled_at`, settlementDiffThresholdCent).
		Joins("LEFT JOIN users AS ru ON ru.id = ro.renter_id").
		Joins("LEFT JOIN users AS ou ON ou.id = ro.owner_id").
		Joins("LEFT JOIN (?) AS oc ON oc.order_id = ro.id", acceptedCheckoutSubquery(r.db.WithContext(ctx))).
		Joins("LEFT JOIN (?) AS p ON p.order_id = ro.id", orderPaymentSubquery(r.db.WithContext(ctx))).
		Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeSubquery(r.db.WithContext(ctx)))

	return r.applyDetailFilters(db, query)
}
