<?php

namespace App\Repositories\Admin;

use Exception;
use Throwable;
use App\Models\User;
use App\Models\Event;
use Illuminate\Http\Request;
use App\Services\ImageService;
use App\Enums\NotificationType;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Repositories\General\NotificationRepository;

class EventRepository
{
    protected $imageService;
    protected $notificationRepository;

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

    public function getAll()
    {
        $events = Event::with([
            'user',
            'image',
        ])
            ->filter(request([
                'search',
            ]))
            ->latest('created_at')
            ->paginate(config('pagination.admin'))
            ->withQueryString();

        return compact('events');
    }

    public function getTrash()
    {
        $events = Event::with([
            'user',
            'image',
        ])
            ->onlyTrashed()
            ->filter(request([
                'search',
            ]))
            ->latest('created_at')
            ->paginate(config('pagination.admin'))
            ->withQueryString();

        return compact('events');
    }

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

        return compact('event');
    }

    public function save(Request $request)
    {
        $loginUser = auth()->user();
        try {
            DB::beginTransaction();

            $event = Event::updateOrCreate(
                ['id' => $request->id],
                [
                    'user_id' => $loginUser->id,
                    'title' => $request->title,
                    'description' => $request->description,
                    'link' => $request->link,
                    'start_time' => $request->start_time,
                    'end_time' => $request->end_time,
                ],
            );

            if ($request->hasFile('image')) {
                $oldImage = $event->image;
                if ($oldImage) {
                    $this->imageService->delete($oldImage->id, Event::class);
                }
                $image = $this->imageService->upload($request->file('image'), Event::class);
                $event->image()->save($image);
            }

            if ($request->id == null) {
                $users = User::user()->get();
                foreach ($users as $user) {
                    $this->notificationRepository->add(
                        userId: $user->id,
                        content: 'Admin has made an event.',
                        imageUrl: $event->image?->url,
                        type: NotificationType::ADMIN->value,
                        redirectLink: route('event.show', $event->id),
                    );
                }
            }

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

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

            throw new Exception('Event saved failed.');
        }
    }

    public function destroy(Event $event)
    {
        try {
            DB::beginTransaction();

            $event->delete();

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

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

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

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

            $event = Event::onlyTrashed()->findOrFail($id);

            $event->restore();

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

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

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