<?php

namespace App\Policies;

use App\Models\UserRole;
use App\Models\Visit;

class VisitPolicy
{
    /**
     * Determine if the user can view the visit.
     */
    public function view(string $userEmail, Visit $visit): bool
    {
        $userRole = UserRole::where('email', $userEmail)->first();

        if (!$userRole) {
            return false;
        }

        // Admins and security can view all visits
        if ($userRole->hasRole(['admin', 'security_member', 'security_admin'])) {
            return true;
        }

        // Regular users can only view their own visits
        return $visit->host_email === $userEmail;
    }

    /**
     * Determine if the user can update the visit.
     */
    public function update(string $userEmail, Visit $visit): bool
    {
        $userRole = UserRole::where('email', $userEmail)->first();

        if (!$userRole) {
            return false;
        }

        // Check if visit can be edited
        if (!$visit->canBeEdited()) {
            return false;
        }

        // Admins can edit any visit
        if ($userRole->hasRole(['admin'])) {
            return true;
        }

        // Users can edit their own visits
        return $visit->host_email === $userEmail;
    }

    /**
     * Determine if the user can delete the visit.
     */
    public function delete(string $userEmail, Visit $visit): bool
    {
        $userRole = UserRole::where('email', $userEmail)->first();

        if (!$userRole) {
            return false;
        }

        // Check if visit can be deleted
        if (!$visit->canBeDeleted()) {
            return false;
        }

        // Admins can delete any visit
        if ($userRole->hasRole(['admin'])) {
            return true;
        }

        // Users can delete their own visits
        return $visit->host_email === $userEmail;
    }

    /**
     * Determine if the user can approve/reject the visit.
     */
    public function review(string $userEmail, Visit $visit): bool
    {
        $userRole = UserRole::where('email', $userEmail)->first();

        if (!$userRole) {
            return false;
        }

        // Only security members and admins can review
        return $userRole->hasRole(['security_member', 'security_admin', 'admin']);
    }
}
