<?php

namespace App\Repositories\Admin;

use Exception;
use Throwable;
use App\Models\User;
use App\Enums\DeletedType;
use App\Enums\NotificationType;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Repositories\General\NotificationRepository;

class UserRepository
{
    protected $notificationRepository;

    public function __construct(NotificationRepository $notificationRepository)
    {
        $this->notificationRepository = $notificationRepository;
    }

    public function getAll()
    {
        $users = User::user()
            ->with([
                'image',
                'profile',
                'ownedGroups',
            ])
            // TODO: Add or not restore
            // ->withTrashed()
            ->filter(request([
                'search',
            ]))
            ->latest('updated_at')
            ->paginate(12)
            ->withQueryString();

        return compact('users');
    }

    public function show($id)
    {
        $user = User::user()
            ->with([
                'image',
                'profile',
                'ownedGroups',
            ])
            ->withTrashed()
            ->find($id);

        return compact('user');
    }

    public function destroy($id)
    {
        $user = User::user()->findOrFail($id);

        try {
            DB::beginTransaction();

            // TODO: Mail the user
            $this->notificationRepository->add(
                userId: $user->id,
                content: 'Admin decided to remove your account.',
                imageUrl: auth()->user()->image?->url,
                type: NotificationType::ADMIN->value,
                redirectLink: '',
            );

            $user->update([
                'deleted_type' => DeletedType::ADMIN,
            ]);
            $user->delete();

            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();

            Log::error(__CLASS__ . '::' . __FUNCTION__ . '[line: ' . __LINE__ . ']Message: ' . $e->getMessage());

            throw new Exception('User deleted failed.');
        }
    }

    public function restore($id)
    {
        try {
            DB::beginTransaction();

            $user = User::onlyTrashed()->findOrFail($id);

            $user->update([
                'deleted_type' => null,
            ]);
            $user->restore();

            DB::commit();
        } catch (Throwable $e) {
            DB::rollBack();

            Log::error(__CLASS__ . '::' . __FUNCTION__ . '[line: ' . __LINE__ . ']Message: ' . $e->getMessage());

            throw new Exception('User restored failed.');
        }
    }
}
