<?php

namespace App\Policies\InternationalTour;

use App\Models\InternationalTour\InternationalTour;
use App\Models\User;

class InternationalTourPolicy
{
    /**
     * Determine whether the user can view any international tours.
     */
    public function viewAny(User $user): bool
    {
        return $user->hasAnyRole(['super-admin', 'agency-owner', 'agency-manager', 'agency-staff']);
    }

    /**
     * Determine whether the user can view the international tour.
     */
    public function view(User $user, InternationalTour $tour): bool
    {
        // Super admin can view all tours
        if ($user->isSuperAdmin()) {
            return true;
        }

        // Agency users can only view their own agency's tours
        return $user->currentAgencyId() === $tour->agency_id;
    }

    /**
     * Determine whether the user can create international tours.
     */
    public function create(User $user): bool
    {
        return $user->hasAnyRole(['agency-owner', 'agency-manager', 'agency-staff'])
            && $user->hasAgency();
    }

    /**
     * Determine whether the user can update the international tour.
     */
    public function update(User $user, InternationalTour $tour): bool
    {
        // Super admin can update all tours
        if ($user->isSuperAdmin()) {
            return true;
        }

        // Must belong to same agency
        if ($user->currentAgencyId() !== $tour->agency_id) {
            return false;
        }

        // Agency owner and manager can update all tours
        if ($user->hasAnyRole(['agency-owner', 'agency-manager'])) {
            return true;
        }

        // Staff can only update tours they created
        if ($user->hasRole('agency-staff')) {
            return $tour->created_by === $user->id;
        }

        return false;
    }

    /**
     * Determine whether the user can delete the international tour.
     */
    public function delete(User $user, InternationalTour $tour): bool
    {
        // Super admin can delete all tours
        if ($user->isSuperAdmin()) {
            return true;
        }

        // Must belong to same agency
        if ($user->currentAgencyId() !== $tour->agency_id) {
            return false;
        }

        // Agency owner can delete all tours
        if ($user->isAgencyOwner()) {
            return true;
        }

        // Agency manager can delete tours except those with bookings
        if ($user->hasRole('agency-manager')) {
            return !$tour->tourDates()->where('sold_count', '>', 0)->exists();
        }

        // Staff cannot delete tours
        return false;
    }
}
