<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\Invoice;
use App\Models\User;

class InvoicePolicy
{
    public function viewAny(User $user): bool
    {
        return true;
    }

    public function view(User $user, Invoice $invoice): bool
    {
        if ($user->hasRole('admin')) {
            return true;
        }

        if ($invoice->user_id === $user->id || $invoice->created_by === $user->id) {
            return true;
        }

        return $invoice->project && (
            $invoice->project->user_id === $user->id
            || $invoice->project->created_by === $user->id
            || ($invoice->project->producer && $invoice->project->producer->user_id === $user->id)
        );
    }

    public function create(User $user): bool
    {
        return true;
    }

    public function update(User $user, Invoice $invoice): bool
    {
        if ($user->hasRole('admin')) {
            return true;
        }

        return ($invoice->created_by === $user->id || $invoice->user_id === $user->id)
            && $invoice->isEditable();
    }

    public function delete(User $user, Invoice $invoice): bool
    {
        if ($user->hasRole('admin')) {
            return true;
        }

        return ($invoice->created_by === $user->id || $invoice->user_id === $user->id)
            && $invoice->isEditable();
    }

    public function pay(User $user, Invoice $invoice): bool
    {
        return $this->view($user, $invoice) && $invoice->isPayable();
    }

    public function approve(User $user, Invoice $invoice): bool
    {
        return $user->hasRole('admin');
    }
}
