<?php

namespace App\Nova\Resources\Ecommerce\Product\Order\Metrics;

use App\Models\Ecommerce\Product\Order\Order;
use App\Models\Ecommerce\Product\Order\Status\OrderStatus;
use DateTimeInterface;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Metrics\Partition;

class OrdersPerStatus extends Partition
{
    /**
     * Calculate the value of the metric.
     */
    public function calculate(NovaRequest $request): mixed
    {
        $model = Order::class;

        if ($request->user()->hasRole('vendor')) {
            $channel = $request->user()->channel();
            $vendor_orders = DB::table('order_items')->where('channel_id', $channel->id)->pluck('order_id');

            $model = Order::whereIntegerInRaw('id', $vendor_orders);
        }

        return $this->count($request, $model, 'status')
            ->colors(OrderStatus::colors())
            ->label(fn ($value) => OrderStatus::formattedStatusFor($value));
    }

    /**
     * Determine the amount of time the results of the metric should be cached.
     *
     * @return \DateTimeInterface|\DateInterval|float|int|null
     */
    public function cacheFor(): DateTimeInterface|DateInterval|float|int|null
    {
        return now()->addMinutes(5);
    }

    /**
     * Get the URI key for the metric.
     */
    public function uriKey(): string
    {
        return 'orders-orders-per-status';
    }

    /**
     * Get the displayable name of the metric
     */
    public function name(): string
    {
        return __('Order Per Status');
    }
}
