<?php

namespace App\Policies;

use App\Models\CoursewarePartner;
use App\Models\User;

class CoursewarePartnerPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->isSuperAdmin() || $user->isAuthorisedPartner();
    }

    public function view(User $user, CoursewarePartner $coursewarePartner): bool
    {
        if ($user->isSuperAdmin()) {
            return true;
        }

        if ($user->isAuthorisedPartner()
            && $user->authorisedPartner
            && $coursewarePartner->authorised_partner_id === $user->authorisedPartner->id) {
            return true;
        }

        if ($user->isPromoter() && $user->promoter) {
            return $coursewarePartner->authorisedPartner()
                ->where('promoter_id', $user->promoter->id)
                ->exists();
        }

        return false;
    }

    public function create(User $user): bool
    {
        return $user->isSuperAdmin() || $user->isAuthorisedPartner();
    }

    public function update(User $user, CoursewarePartner $coursewarePartner): bool
    {
        return $this->manage($user, $coursewarePartner);
    }

    public function delete(User $user, CoursewarePartner $coursewarePartner): bool
    {
        return $this->manage($user, $coursewarePartner);
    }

    public function approve(User $user, CoursewarePartner $coursewarePartner): bool
    {
        return $this->manage($user, $coursewarePartner);
    }

    private function manage(User $user, CoursewarePartner $coursewarePartner): bool
    {
        if ($user->isSuperAdmin()) {
            return true;
        }

        return $user->isAuthorisedPartner()
            && $user->authorisedPartner
            && $coursewarePartner->authorised_partner_id === $user->authorisedPartner->id;
    }
}
