<?php

namespace App\Modules\Sales\Policies;

use App\Models\User;
use App\Modules\Sales\Models\SalesOrder;
use App\Modules\Sales\Services\SalesOrderLifecycleRules;
use App\Modules\Sales\Support\SalesOrderLifecycleStatus;

class SalesOrderPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->can('sales.orders.view');
    }

    public function view(User $user, SalesOrder $salesOrder): bool
    {
        return $user->can('sales.orders.view', $salesOrder);
    }

    public function allocate(User $user, SalesOrder $salesOrder): bool
    {
        if (! $user->can('sales.orders.operate', $salesOrder)) {
            return false;
        }
        $s = SalesOrderLifecycleStatus::tryFrom((string) $salesOrder->status);

        return $s !== null && SalesOrderLifecycleRules::allowsAllocation($s);
    }

    public function fulfill(User $user, SalesOrder $salesOrder): bool
    {
        if (! $user->can('sales.orders.operate', $salesOrder)) {
            return false;
        }
        $s = SalesOrderLifecycleStatus::tryFrom((string) $salesOrder->status);

        return $s !== null && SalesOrderLifecycleRules::allowsFulfillment($s);
    }

    public function cancel(User $user, SalesOrder $salesOrder): bool
    {
        if (! $user->can('sales.orders.operate', $salesOrder)) {
            return false;
        }
        $s = SalesOrderLifecycleStatus::tryFrom((string) $salesOrder->status);

        return $s !== null && SalesOrderLifecycleRules::allowsCancel($s);
    }
}
