<?php

namespace App\Support;

use App\Models\Attachment;
use App\Models\Ticket;
use App\Models\User;

class AttachmentAccess
{
    public static function canAccess(?Attachment $attachment, ?User $user): bool
    {
        if (!$attachment || !$user) {
            return false;
        }

        if (class_exists(OrganizationScope::class) && OrganizationScope::isSuperAdmin($user)) {
            return true;
        }

        if ($user->supportDeskIsSuperAdmin()) {
            return true;
        }

        $role = $user->supportDeskRole();

        $ticket = $attachment->relationLoaded('ticket')
            ? $attachment->ticket
            : ($attachment->ticket_id ? Ticket::find($attachment->ticket_id) : null);

        if ($ticket) {
            if ($role === 'user') {
                return (string) $ticket->requester_id === (string) $user->id;
            }

            if ($role === 'admin') {
                if (class_exists(OrganizationScope::class)) {
                    return OrganizationScope::canAccessTicket($ticket, $user);
                }

                $organization = trim((string) ($user->department ?? ''));

                return $organization !== '' && $ticket->department === $organization;
            }

            return true;
        }

        if ($attachment->uploaded_by_id) {
            return (string) $attachment->uploaded_by_id === (string) $user->id;
        }

        return $role === 'admin';
    }
}
