<?php

namespace App\Policies;

use App\Models\User;
use App\Models\Event;
use App\Models\Calendar;

class EventPolicy
{
    /* -------------------------------------------------
     |  Helper: does the user own the calendar?
     |-------------------------------------------------*/
    private function ownsCalendar(User $user, Calendar $calendar): bool
    {
        return $calendar->instances()
            ->where('principaluri', 'principals/'.$user->email)
            ->exists();
    }

    /* -------------------------------------------------
     |  List all events (e.g. /calendar/{id}/events)
     |-------------------------------------------------*/
    public function viewAny(User $user): bool
    {
        return true;   // authenticated users can query their events
    }

    /* -------------------------------------------------
     |  Show a single event  (/calendar/{id}/event/{event})
     |-------------------------------------------------*/
    public function view(User $user, Event $event): bool
    {
        return $this->ownsCalendar($user, $event->calendar);
    }

    /* -------------------------------------------------
     |  Create an event (needs parent calendar)
     |-------------------------------------------------*/
    public function create(User $user, Calendar $calendar): bool
    {
        return $this->ownsCalendar($user, $calendar);
    }

    /* -------------------------------------------------
     |  Update / delete use same ownership rule
     |-------------------------------------------------*/
    public function update(User $user, Event $event): bool
    {
        return $this->view($user, $event);
    }

    public function delete(User $user, Event $event): bool
    {
        return $this->view($user, $event);
    }

    /* -------------------------------------------------
     |  Not supported
     |-------------------------------------------------*/
    public function restore(User $user, Event $event): bool
    {
        return false;
    }

    public function forceDelete(User $user, Event $event): bool
    {
        return false;
    }
}
