<?php

namespace App\Modules\Payroll\Policies;

use App\Models\User;
use App\Modules\Payroll\Models\PayrollPeriod;
use App\Modules\Payroll\Support\PayrollPeriodStatus;

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

    public function view(User $user, PayrollPeriod $period): bool
    {
        return $user->can('payroll.view') && $this->sameTenant($user, $period);
    }

    public function create(User $user): bool
    {
        return $user->can('payroll.process');
    }

    public function process(User $user, PayrollPeriod $period): bool
    {
        return $user->can('payroll.process')
            && $this->sameTenant($user, $period)
            && $period->status === PayrollPeriodStatus::DRAFT;
    }

    public function finalize(User $user, PayrollPeriod $period): bool
    {
        return $user->can('payroll.finalize')
            && $this->sameTenant($user, $period)
            && $period->status === PayrollPeriodStatus::PROCESSING;
    }

    public function manageAdjustments(User $user, PayrollPeriod $period): bool
    {
        return $user->can('payroll.adjustments.manage')
            && $this->sameTenant($user, $period)
            && $period->status === PayrollPeriodStatus::DRAFT;
    }

    private function sameTenant(User $user, PayrollPeriod $period): bool
    {
        return (int) $user->tenant_id === (int) $period->tenant_id;
    }
}
