<?php

namespace App\Services\Dav;

use Sabre\DAV\PropPatch;
use Sabre\DAVACL\PrincipalBackend\AbstractBackend;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class LaravelSabrePrincipalBackend extends AbstractBackend
{
    public function getPrincipalsByPrefix($prefixPath)
    {
        return User::all()->map(function ($user) {
            return [
                'uri' => 'principals/' . $user->email,
                '{DAV:}displayname' => $user->name,
            ];
        })->toArray();
    }

    public function getPrincipalByPath($path)
    {
        \Log::info('getPrincipalByPath', ['path' => $path]);

        $email = basename($path);
        $user = User::where('email', $email)->first();

        if ($user) {
            return [
                'uri' => 'principals/' . $user->email,
                '{DAV:}displayname' => $user->name,
            ];
        }

        \Log::warning('No user found for principal path', ['key' => $key]);
        return null;
    }

    public function updatePrincipal($path, PropPatch $propPatch)
    {
        // Not implementing updates to principal properties
        $propPatch->handle([], fn () => true);
        return false;
    }

    public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof')
    {
        // No search functionality
        return [];
    }

    public function findByUri($uri, $principalPrefix)
    {
        // No group lookup support
        return null;
    }

    public function getGroupMemberSet($principal)
    {
        // Not supporting group principals
        return [];
    }

    public function getGroupMembership($principal)
    {
        // Not supporting group memberships
        return [];
    }

    public function setGroupMemberSet($principal, array $members)
    {
        // Not supporting modifying groups
        throw new \Sabre\DAV\Exception\MethodNotAllowed('Setting group members not supported.');
    }
}
