<?php

namespace App\Policies;

use App\Enums\AppRole;
use App\Models\Partnership;
use App\Models\User;
use App\Models\WorkspaceMember;

class PartnershipPolicy
{
    public function view(User $user, Partnership $partnership): bool
    {
        return $partnership->isVisibleTo($user);
    }

    public function create(User $user): bool
    {
        return false;
    }

    public function update(User $user, Partnership $partnership): bool
    {
        $workspace = $partnership->workspace;
        $member = WorkspaceMember::query()
            ->where('workspace_id', $workspace->id)
            ->where('user_id', $user->id)
            ->first();

        if ($member === null) {
            return false;
        }

        $role = $member->role instanceof AppRole ? $member->role : AppRole::from((string) $member->role);

        if (in_array($role, [AppRole::Influencer, AppRole::Assistant], true)) {
            return true;
        }

        if ($role === AppRole::Restaurant) {
            return (int) $partnership->managed_by_restaurant === (int) $user->id;
        }

        return false;
    }

    public function delete(User $user, Partnership $partnership): bool
    {
        $workspace = $partnership->workspace;
        $member = WorkspaceMember::query()
            ->where('workspace_id', $workspace->id)
            ->where('user_id', $user->id)
            ->first();

        if ($member === null) {
            return false;
        }

        $role = $member->role instanceof AppRole ? $member->role : AppRole::from((string) $member->role);

        return $role === AppRole::Influencer;
    }
}
