<?php

namespace App\Http\Controllers\APIS\AdminApi;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class LoginController extends Controller
{
    public function adminLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [

            'email' => 'required|string',
            'password' => 'required|string',
        ]);
        if ($validator->fails()) {
            return jsonResponseWithErrorMessage($validator->errors()->first(), 400);
        }



        $baseUrl = env('THINGSBOARD_URL', 'http://65.0.131.117:8080');

        try {
            $response = Http::withHeaders([
                'accept' => 'application/json',
                'Content-Type' => 'application/json',
            ])->post("{$baseUrl}api/auth/login", [
                'username' => $request->email,
                'password' => $request->password,
            ]);

            if ($response->successful()) {
                $token = $response->json('token');

                return jsonResponseWithSuccessMessage(__('Login successful'), $token, 1);
            } else {
                return response()->json([
                    'message' => __($response->json('message') ?? 'Invalid credentials')
                ], 401);
            }
        } catch (Exception $e) {
            Log::error("Login Error: " . $e->getMessage());
            return response()->json([
                'message' => __('auth.something_went_wrong')
            ], 500);
        }
    }
}
