<?php

namespace App\Policies;

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

class WorkspacePolicy
{
    public function update(User $user, Workspace $workspace): bool
    {
        return (int) $workspace->owner_id === (int) $user->id;
    }

    public function inviteMembers(User $user, Workspace $workspace): bool
    {
        return $this->memberHasRole($user, $workspace, [AppRole::Influencer, AppRole::Assistant]);
    }

    public function manageMembers(User $user, Workspace $workspace): bool
    {
        return $this->memberHasRole($user, $workspace, [AppRole::Influencer, AppRole::Assistant]);
    }

    public function createPartnership(User $user, Workspace $workspace): bool
    {
        return $this->memberHasRole($user, $workspace, [AppRole::Influencer, AppRole::Assistant]);
    }

    /**
     * @param  array<int, AppRole>  $roles
     */
    private function memberHasRole(User $user, Workspace $workspace, array $roles): bool
    {
        $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::tryFrom((string) $member->role);
        if ($role === null) {
            return false;
        }

        return in_array($role, $roles, true);
    }
}
