<?php

namespace App\Policies;

use App\Models\Actual;
use App\Models\User;

class ActualPolicy
{
    /**
     * Determine whether the user can view any actuals.
     */
    public function viewAny(User $user): bool
    {
        return true;
    }

    /**
     * Determine whether the user can view a specific actual.
     */
    public function view(User $user, Actual $actual): bool
    {
        return true;
    }

    /**
     * Determine whether the user can create actuals.
     *
     * Superusers and managers can create actuals for any team member.
     * Developers can only create actuals for themselves (if linked to a team member).
     */
    public function create(User $user, ?string $teamMemberId = null): bool
    {
        // Superusers and managers can create any actual
        if (in_array($user->role, ['superuser', 'manager'])) {
            return true;
        }

        // Developers can only create actuals for their own team member record
        if ($user->role === 'developer') {
            // If no team_member_id provided, deny (defensive)
            if ($teamMemberId === null) {
                return false;
            }

            // Check if user is linked to this team member
            return $user->team_member_id === $teamMemberId;
        }

        return false;
    }

    /**
     * Determine whether the user can update the actual.
     *
     * Superusers and managers can update any actual.
     * Developers can only update their own actuals.
     */
    public function update(User $user, Actual $actual): bool
    {
        // Superusers and managers can update any actual
        if (in_array($user->role, ['superuser', 'manager'])) {
            return true;
        }

        // Developers can only update their own actuals
        if ($user->role === 'developer') {
            return $user->team_member_id === $actual->team_member_id;
        }

        return false;
    }

    /**
     * Determine whether the user can delete the actual.
     *
     * Superusers and managers can delete any actual.
     * Developers can only delete their own actuals.
     */
    public function delete(User $user, Actual $actual): bool
    {
        // Superusers and managers can delete any actual
        if (in_array($user->role, ['superuser', 'manager'])) {
            return true;
        }

        // Developers can only delete their own actuals
        if ($user->role === 'developer') {
            return $user->team_member_id === $actual->team_member_id;
        }

        return false;
    }
}
