<?php

namespace App\Repositories\Eloquent;

use App\Models\Product;
use Illuminate\Database\Eloquent\Model;

class ProductRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Product();
    }

    public function all(array $columns = ['*']): \Illuminate\Database\Eloquent\Collection
    {
        return $this->model->with(['category', 'optionSets', 'innerOptionSets'])->get($columns);
    }

    public function findBySlug(string $slug): ?Product
    {
        return $this->model->where('slug', $slug)->first();
    }

    public function getActive()
    {
        return $this->model->active()->with(['category', 'optionSets.items', 'innerOptionSets.items'])->get();
    }

    public function getByCategory(int $categoryId)
    {
        return $this->model->byCategory($categoryId)->active()->get();
    }

    public function getWithRelations(int $id): ?Product
    {
        return $this->model->with([
            'category',
            'optionSets.items',
            'innerOptionSets.items'
        ])->find($id);
    }

    public function getForBranch(int $branchId)
    {
        return $this->model->active()
            ->whereHas('branchProducts', function ($query) use ($branchId) {
                $query->where('branch_id', $branchId)->where('is_available', true);
            })
            ->with([
                'category',
                'optionSets.items' => fn($q) => $q->where('is_active', true)->orderBy('sort_order'),
                'innerOptionSets.items' => fn($q) => $q->where('is_active', true)->orderBy('sort_order'),
                'branchProducts' => function ($query) use ($branchId) {
                    $query->where('branch_id', $branchId);
                }
            ])
            ->get()
            ->map(function ($product) use ($branchId) {
                // Only check batches for products that require production
                if ($product->requires_production) {
                    // Check for active production batches with remaining scoops
                    $availableScoops = \App\Models\ProductionBatch::where('branch_id', $branchId)
                        ->where('product_id', $product->id)
                        ->where('status', 'active')
                        ->where('remaining_scoops', '>', 0)
                        ->where(function ($q) {
                            $q->whereNull('expires_at')
                              ->orWhere('expires_at', '>', now());
                        })
                        ->sum('remaining_scoops');

                    $product->available_scoops = (int) $availableScoops;
                    $product->has_stock = $availableScoops > 0;
                } else {
                    // Non-scoop products are always available (no batches needed)
                    $product->available_scoops = 0;
                    $product->has_stock = true;
                }

                return $product;
            });
    }

    public function syncOptionSets(int $productId, array $optionSetIds): void
    {
        $product = $this->find($productId);
        $product->optionSets()->sync($optionSetIds);
    }

    public function syncInnerOptionSets(int $productId, array $innerOptionSetIds): void
    {
        $product = $this->find($productId);
        $product->innerOptionSets()->sync($innerOptionSetIds);
    }
}
