package admindashboard

import (
	"time"

	"hfb_sys/backend/internal/model"

	"gorm.io/gorm"
)

type Repository struct {
	db *gorm.DB
}

func NewRepository(db *gorm.DB) *Repository {
	return &Repository{db: db}
}

func (r *Repository) Summary() (*DashboardDTO, error) {
	now := time.Now()
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	metrics := MetricsDTO{}
	pending := PendingDTO{}

	if err := r.db.Model(&model.User{}).Count(&metrics.TotalUsers).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.User{}).Where("realname_status = ?", "verified").Count(&metrics.VerifiedUsers).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalListing{}).Count(&metrics.TotalListings).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalListing{}).Where("status = ? AND review_status = ?", "published", "approved").Count(&metrics.PublishedListings).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalOrder{}).Count(&metrics.TotalOrders).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalOrder{}).Where("status = ?", "renting").Count(&metrics.RentingOrders).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalOrder{}).Where("created_at >= ?", today).Count(&metrics.TodayOrders).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.WalletLedger{}).
		Select("COALESCE(SUM(amount), 0)").
		Where("created_at >= ?", today).
		Scan(&metrics.TodayLedgerAmount).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalListing{}).Where("review_status = ?", "pending").Count(&pending.ListingReviews).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.Dispute{}).Where("status IN ?", []string{"open", "processing"}).Count(&pending.Disputes).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalOrder{}).Where("status = ? AND handoff_status IN ?", "pending_handoff", []string{"pending_owner", "pending_renter_confirm"}).Count(&pending.PendingHandoffs).Error; err != nil {
		return nil, err
	}
	if err := r.db.Model(&model.RentalOrder{}).Where("status IN ?", []string{"pending_checkout_confirm", "pending_checkout_accept"}).Count(&pending.PendingReturnConfirms).Error; err != nil {
		return nil, err
	}
	recentOrders, err := r.recentOrders()
	if err != nil {
		return nil, err
	}
	recentDisputes, err := r.recentDisputes()
	if err != nil {
		return nil, err
	}
	return &DashboardDTO{
		Metrics:        metrics,
		Pending:        pending,
		RecentOrders:   recentOrders,
		RecentDisputes: recentDisputes,
		GeneratedAt:    now,
	}, nil
}

func (r *Repository) recentOrders() ([]RecentOrderDTO, error) {
	rows := make([]RecentOrderDTO, 0)
	err := r.db.Table("rental_orders AS o").
		Select("o.id, o.order_no, a.title, o.renter_id, o.owner_id, o.status, o.rent_amount, o.deposit_amount, o.created_at").
		Joins("JOIN game_accounts AS a ON a.id = o.account_id").
		Order("o.id DESC").
		Limit(8).
		Scan(&rows).Error
	return rows, err
}

func (r *Repository) recentDisputes() ([]RecentDisputeDTO, error) {
	rows := make([]RecentDisputeDTO, 0)
	err := r.db.Table("disputes AS d").
		Select("d.id, d.order_id, o.order_no, a.title, d.type, d.status, d.initiator_id, d.created_at").
		Joins("JOIN rental_orders AS o ON o.id = d.order_id").
		Joins("JOIN game_accounts AS a ON a.id = o.account_id").
		Order("d.id DESC").
		Limit(8).
		Scan(&rows).Error
	return rows, err
}
