<?php

namespace App\Http\Controllers\Meet\Concerns;

use App\Models\Member;
use App\Models\Organization;
use App\Services\Meet\MeetPermissions;
use App\Services\Meet\OrganizationResolver;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

trait ScopesToAccount
{
    protected function ownerRef(Request $request): string
    {
        return (string) $request->user()->public_id;
    }

    protected function organization(Request $request): Organization
    {
        $organization = $request->attributes->get('meet.organization')
            ?? app(OrganizationResolver::class)->resolveForUser($request->user());

        abort_unless($organization, 404);

        return $organization;
    }

    protected function member(Request $request): ?Member
    {
        return $request->attributes->get('meet.member')
            ?? app(OrganizationResolver::class)->memberFor($request->user(), $this->organization($request));
    }

    protected function authorizeAbility(Request $request, string $ability): void
    {
        abort_unless(
            app(MeetPermissions::class)->can($this->member($request), $ability),
            403,
        );
    }

    protected function authorizeOwner(Request $request, Model $model): void
    {
        abort_unless($model->getAttribute('owner_ref') === $this->ownerRef($request), 404);
    }

    protected function scopeToBranch(Request $request, Builder $query, string $column = 'branch_id'): Builder
    {
        $branchId = app(OrganizationResolver::class)->branchScope($this->member($request));

        if ($branchId !== null) {
            $query->where($column, $branchId);
        }

        return $query;
    }
}
