<?php

namespace App\Repositories;

use App\Models\Order;
use App\Repositories\Interfaces\OrderRepositoryInterface;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class OrderRepository extends BaseRepository implements OrderRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    protected function resolveModel(): Model
    {
        return new Order();
    }

    /**
     * {@inheritdoc}
     */
    public function getByStatus(string $status): Collection
    {
        return $this->where('status', $status)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function getByCustomer(int $customerId): Collection
    {
        return $this->where('user_id', $customerId)->all();
    }

    /**
     * {@inheritdoc}
     */
    public function getByType(string $type): self
    {
        $this->query = $this->query->where('order_type', $type);
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getDrafts(): Collection
    {
        return $this->getByStatus('DRAFT');
    }

    /**
     * {@inheritdoc}
     */
    public function getConfirmed(): Collection
    {
        return $this->getByStatus('CONFIRMED');
    }

    /**
     * {@inheritdoc}
     */
    public function orderDateBetween(string $from, string $to): self
    {
        $this->query = $this->query
            ->whereDate('order_date', '>=', $from)
            ->whereDate('order_date', '<=', $to);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function findByOrderNumber(string $orderNumber): ?Order
    {
        return $this->findFirstBy('order_number', $orderNumber);
    }

    /**
     * {@inheritdoc}
     */
    public function withDetails(): self
    {
        return $this->with(['user', 'lines.product']);
    }

    /**
     * Filter by customer ID.
     */
    public function filterByCustomer(?int $customerId): self
    {
        if ($customerId) {
            $this->query = $this->query->where('user_id', $customerId);
        }
        return $this;
    }

    /**
     * Filter by status.
     */
    public function filterByStatus(?string $status): self
    {
        if ($status) {
            $this->query = $this->query->where('status', $status);
        }
        return $this;
    }

    /**
     * Filter by order type.
     */
    public function filterByOrderType(?string $type): self
    {
        if ($type) {
            $this->query = $this->query->where('order_type', $type);
        }
        return $this;
    }
}
