<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\UserStatsService;
use App\Support\UsernamePolicy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FavouritesController extends Controller
{
    public function index(Request $request, $userId = null, $username = null)
    {
        $user = $this->resolveLegacyFavouritesUser($request, $userId, $username);
        if (! $user) {
            abort(404);
        }

        return redirect()->route('profile.show', [
            'username' => strtolower((string) $user->username),
            'tab' => 'favourites',
        ], 301);
    }

    public function destroy(Request $request, $userId, $artworkId)
    {
        $auth = $request->user();
        if (! $auth || $auth->id != (int)$userId) {
            abort(403);
        }

        $creatorId = (int) DB::table('artworks')->where('id', (int) $artworkId)->value('user_id');

        DB::table('artwork_favourites')->where('user_id', (int) $userId)->where('artwork_id', (int) $artworkId)->delete();

        if ($creatorId) {
            app(UserStatsService::class)->decrementFavoritesReceived($creatorId);
        }

        $username = strtolower((string) ($auth->username ?? DB::table('users')->where('id', (int) $userId)->value('username') ?? ''));

        return redirect()->route('profile.show', [
            'username' => $username,
            'tab' => 'favourites',
        ])->with('status', 'Removed from favourites');
    }

    private function resolveLegacyFavouritesUser(Request $request, mixed $userId, mixed $username): ?User
    {
        if (is_string($userId) && ! is_numeric($userId) && $username === null) {
            $username = $userId;
            $userId = null;
        }

        if (is_numeric($userId)) {
            return User::query()->find((int) $userId);
        }

        if (is_string($username) && $username !== '') {
            $normalized = UsernamePolicy::normalize($username);

            return User::query()->whereRaw('LOWER(username) = ?', [$normalized])->first();
        }

        return $request->user();
    }
}
