<?php

namespace App\Policies;

use App\Models\ClinicalHistory;
use App\Models\User;

/**
 * El historial clínico es información sensible. Solo:
 *  - super_admin (no debería usarlo, pero técnicamente accede vía before)
 *  - company_admin de la misma empresa
 *  - employee con permiso `clinical_history.view` (asignado por su admin)
 *
 * Toda lectura/escritura debe loggearse vía spatie/laravel-activitylog.
 */
class ClinicalHistoryPolicy
{
    public function before(User $user): ?bool
    {
        return $user->isSuperAdmin() ? true : null;
    }

    public function viewAny(User $user): bool
    {
        return $user->isCompanyAdmin()
            || ($user->isEmployee() && $user->can('clinical_history.view'));
    }

    public function view(User $user, ClinicalHistory $history): bool
    {
        if ($user->company_id !== $history->company_id) {
            return false;
        }

        if ($user->isCompanyAdmin()) {
            return true;
        }

        return $user->isEmployee() && $user->can('clinical_history.view');
    }

    public function create(User $user): bool
    {
        if ($user->company_id === null) return false;
        return $user->isCompanyAdmin()
            || ($user->isEmployee() && $user->can('clinical_history.edit'));
    }

    public function update(User $user, ClinicalHistory $history): bool
    {
        if ($user->company_id !== $history->company_id) return false;
        return $user->isCompanyAdmin()
            || ($user->isEmployee() && $user->can('clinical_history.edit'));
    }

    public function delete(User $user, ClinicalHistory $history): bool
    {
        return $user->isCompanyAdmin() && $user->company_id === $history->company_id;
    }
}
