<?php

namespace App\Repositories\Eloquent;

use App\Models\ScoopSale;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class ScoopSaleRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new ScoopSale();
    }

    public function getDailySalesByProduct(int $branchId, string $date): Collection
    {
        return $this->model
            ->forBranch($branchId)
            ->forDate($date)
            ->select('product_id', DB::raw('SUM(scoop_count) as total_scoops'), DB::raw('SUM(sale_price) as total_sales'))
            ->groupBy('product_id')
            ->with('product:id,name')
            ->get();
    }

    public function getSalesBetweenDates(int $branchId, string $startDate, string $endDate): Collection
    {
        return $this->model
            ->forBranch($branchId)
            ->betweenDates($startDate, $endDate)
            ->select(
                'product_id',
                DB::raw('DATE(sold_at) as sale_date'),
                DB::raw('SUM(scoop_count) as total_scoops'),
                DB::raw('SUM(sale_price) as total_sales')
            )
            ->groupBy('product_id', DB::raw('DATE(sold_at)'))
            ->with('product:id,name')
            ->orderBy('sale_date')
            ->get();
    }

    public function getTotalScoopsSold(int $branchId, ?string $date = null): int
    {
        $query = $this->model->forBranch($branchId);

        if ($date) {
            $query->forDate($date);
        }

        return $query->sum('scoop_count');
    }

    public function getScoopSalesForOrder(int $orderId): Collection
    {
        return $this->model->where('order_id', $orderId)->with(['product', 'productionBatch'])->get();
    }
}
