<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserActivity;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    public function show(Request $request, int $userId)
    {
        $user = User::findOrFail($userId);
        return ApiResponse::success('User profile', AuthController::userPayload($user));
    }

    public function update(Request $request, int $userId)
    {
        $user = User::findOrFail($userId);
        if ($request->user()->id !== $user->id && $request->user()->role !== 'supervisor') {
            return ApiResponse::error('Forbidden', null, 403);
        }
        $data = $request->validate([
            'fullName' => 'nullable|string|max:255',
            'email' => 'nullable|email',
        ]);
        if (isset($data['fullName'])) $user->full_name = $data['fullName'];
        if (isset($data['email'])) $user->email = $data['email'];
        $user->save();
        return ApiResponse::success('Profile updated', AuthController::userPayload($user));
    }

    public function uploadProfilePicture(Request $request, int $userId)
    {
        $user = User::findOrFail($userId);
        $request->validate(['file' => 'required|image|max:5120']);
        $stored = $request->file('file')->store('Uploads/Profile', 'public');
        $user->profile_picture = Storage::url($stored);
        $user->save();
        return ApiResponse::success('Profile picture updated', ['profile_picture' => $user->profile_picture]);
    }

    public function deleteProfilePicture(Request $request, int $userId)
    {
        $user = User::findOrFail($userId);
        $user->profile_picture = null;
        $user->save();
        return ApiResponse::success('Profile picture removed');
    }

    public function activity(Request $request, int $userId)
    {
        $items = UserActivity::where('user_id', $userId)->orderByDesc('id')->paginate(20);
        return ApiResponse::paginated('User activity', $items);
    }
}
