<?php

namespace App\Services;

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

class WorkspaceContextResolver
{
    /**
     * Pick the collab board workspace (mirrors partnership-pal pickPrimaryMembership).
     *
     * @return array{0: Workspace, 1: AppRole}|array{0: null, 1: null}
     */
    public function resolve(User $user): array
    {
        $rows = WorkspaceMember::query()
            ->where('user_id', $user->id)
            ->with('workspace')
            ->get();

        if ($rows->isEmpty()) {
            return [null, null];
        }

        $sorted = $rows->sort(function (WorkspaceMember $a, WorkspaceMember $b) use ($user) {
            $ra = self::rank($a->role);
            $rb = self::rank($b->role);
            if ($ra !== $rb) {
                return $ra <=> $rb;
            }

            $aOwn = $a->workspace !== null && (int) $a->workspace->owner_id === (int) $user->id;
            $bOwn = $b->workspace !== null && (int) $b->workspace->owner_id === (int) $user->id;
            if ($aOwn !== $bOwn) {
                return $aOwn ? 1 : -1;
            }

            $ta = $a->created_at?->getTimestamp() ?? 0;
            $tb = $b->created_at?->getTimestamp() ?? 0;

            return $tb <=> $ta;
        })->values();

        /** @var WorkspaceMember $first */
        $first = $sorted->first();
        $workspace = $first->workspace;
        if ($workspace === null) {
            return [null, null];
        }

        return [$workspace, $first->role instanceof AppRole ? $first->role : AppRole::from($first->role)];
    }

    private static function rank(AppRole|string $role): int
    {
        $r = $role instanceof AppRole ? $role : AppRole::from($role);

        return match ($r) {
            AppRole::Assistant => 0,
            AppRole::Influencer => 1,
            AppRole::Agency => 2,
            AppRole::Restaurant => 3,
        };
    }
}
