<?php

namespace App\Repositories\General;

use Exception;
use Throwable;
use App\Models\User;
use App\Models\Friend;
use App\Enums\DeletedType;
use Illuminate\Http\Request;
use App\Services\ImageService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserRepository
{
    protected $imageService;

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

    public function show($id)
    {
        $user = User::with([
            'profile',
            'image',
            // TODO: Remove
            'posts.images',
            'posts.user.image',
            'posts.comments.user.image',
            'posts.comments.likes.image',
            'posts.likes.image',
            'posts.group.images',
        ])->findOrFail($id);

        $posts = $user->posts()->with([
            'images',
            'user.image',
            'comments.user.image',
            'comments.likes.image',
            'likes.image',
            'group.images',
        ])
            ->available()
            ->latest('updated_at')
            ->paginate(12)
            ->withQueryString();

        $friendship = null;
        $loginUserId = auth()->id();
        if ($loginUserId) {
            $friendship = Friend::getByUsers($loginUserId, $user->id)->first();
        }

        return compact('user', 'friendship', 'posts');
    }

    public function showCount($id)
    {
        $user = User::findOrFail($id);

        $postsCount = $user->posts()->count();
        $commentsCount = $user->comments()->count();
        $friendsCount = $user->getFriends()->count();
        $postLikesCount = $user->postLikes()->count();

        return compact('postsCount', 'commentsCount', 'friendsCount', 'postLikesCount');
    }

    public function destroy(Request $request)
    {
        $user = User::owned()->first();

        auth()->logout();

        try {
            DB::beginTransaction();

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

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

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

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

        $request->session()->invalidate();
        $request->session()->regenerateToken();
    }
}
