<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Agent;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * POST /api/login
     * Accepts JSON { username, password } — plain-text comparison kept for
     * backward compatibility with existing agent records.
     * Upgrade to Hash::check() once you hash your agent passwords.
     */
    public function login(Request $request)
    {
        $username = $request->input('username', '');
        $password = $request->input('password', '');

        if ($username === '' || $password === '') {
            return response()->json(['success' => false, 'message' => 'Missing credentials']);
        }

        $agent = Agent::where('username', $username)->first();

        // Plain-text check (matches original PHP behaviour).
        // Swap this line for Hash::check($password, $agent->password)
        // once you migrate passwords to bcrypt.
        if (!$agent || $agent->password !== $password) {
            return response()->json(['success' => false, 'message' => 'Invalid username or password']);
        }

        return response()->json([
            'success' => true,
            'message' => 'Login successful',
            'agent'   => [
                'id'       => $agent->id,
                'username' => $agent->username,
                'name'     => $agent->name,
            ],
        ]);
    }
}
