<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    // POST /api/auth/register
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name'                  => 'required|string|max:100',
            'email'                 => 'required|email|max:255|unique:users,email',
            'password'              => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation error',
                'data'    => $validator->errors()->all(),
            ], 422);
        }

        $user = User::create([
            'username' => $this->generateUsername($request->name),
            'name'     => $request->name,
            'email'    => $request->email,
            'password' => $request->password, // model casts to hashed
            'status'   => 0,
        ]);

        $token = $user->createToken('api-token')->plainTextToken;

        return response()->json([
            'status'  => 'success',
            'message' => 'Registration successful',
            'data'    => [
                'token' => $token,
                'user'  => $this->formatUser($user),
            ],
        ], 201);
    }

    // POST /api/auth/login
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'    => 'required|email',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation error',
                'data'    => $validator->errors()->all(),
            ], 422);
        }

        $user = User::where('email', $request->email)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Invalid email or password',
            ], 401);
        }

        if ($user->status == 1) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Your account has been blocked. Please contact support.',
            ], 403);
        }

        $token = $user->createToken('api-token')->plainTextToken;

        return response()->json([
            'status'  => 'success',
            'message' => 'Login successful',
            'data'    => [
                'token' => $token,
                'user'  => $this->formatUser($user),
            ],
        ]);
    }

    // POST /api/auth/google
    // Flutter sends the Google ID token; we verify with Google and upsert the user.
    public function googleAuth(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id_token' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation error',
                'data'    => $validator->errors()->all(),
            ], 422);
        }

        // Verify token with Google
        $response = Http::get('https://oauth2.googleapis.com/tokeninfo', [
            'id_token' => $request->id_token,
        ]);

        if (!$response->successful()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Invalid Google token',
            ], 401);
        }

        $googleUser = $response->json();

        if (empty($googleUser['sub']) || empty($googleUser['email'])) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Could not retrieve Google account info',
            ], 401);
        }

        // Find or create user
        $user = User::where('google_id', $googleUser['sub'])
                    ->orWhere('email', $googleUser['email'])
                    ->first();

        if ($user) {
            // Update Google fields if missing
            $user->google_id = $user->google_id ?? $googleUser['sub'];
            $user->avatar    = $user->avatar    ?? ($googleUser['picture'] ?? null);
            $user->save();
        } else {
            $user = User::create([
                'username'          => $this->generateUsername($googleUser['name'] ?? $googleUser['email']),
                'name'              => $googleUser['name']    ?? 'User',
                'email'             => $googleUser['email'],
                'google_id'         => $googleUser['sub'],
                'avatar'            => $googleUser['picture'] ?? null,
                'email_verified_at' => now(),
                'password'          => Hash::make(Str::random(32)),
                'status'            => 0,
            ]);
        }

        if ($user->status == 1) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Your account has been blocked. Please contact support.',
            ], 403);
        }

        $token = $user->createToken('api-token')->plainTextToken;

        return response()->json([
            'status'  => 'success',
            'message' => 'Google sign-in successful',
            'data'    => [
                'token' => $token,
                'user'  => $this->formatUser($user),
            ],
        ]);
    }

    // POST /api/auth/logout  (requires auth:sanctum)
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'status'  => 'success',
            'message' => 'Logged out successfully',
        ]);
    }

    // GET /api/auth/me  (requires auth:sanctum)
    public function me(Request $request)
    {
        return response()->json([
            'status' => 'success',
            'data'   => $this->formatUser($request->user()),
        ]);
    }

    // PUT /api/auth/profile  (requires auth:sanctum)
    public function updateProfile(Request $request)
    {
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'name'     => 'sometimes|string|max:100',
            'username' => 'sometimes|string|max:50|unique:users,username,' . $user->id,
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Validation error',
                'data'    => $validator->errors()->all(),
            ], 422);
        }

        if ($request->filled('name'))     $user->name     = $request->name;
        if ($request->filled('username')) $user->username = $request->username;
        $user->save();

        return response()->json([
            'status'  => 'success',
            'message' => 'Profile updated',
            'data'    => $this->formatUser($user),
        ]);
    }

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    private function formatUser(User $user): array
    {
        return [
            'id'       => $user->id,
            'name'     => $user->name,
            'username' => $user->username,
            'email'    => $user->email,
            'avatar'   => $user->avatar_url,
            'status'   => $user->status,
        ];
    }

    private function generateUsername(string $base): string
    {
        $slug = Str::slug(Str::limit($base, 30, ''), '_');
        $candidate = $slug ?: 'user';
        $suffix = 1;
        while (User::where('username', $candidate)->exists()) {
            $candidate = $slug . '_' . $suffix++;
        }
        return $candidate;
    }
}
