<?php

namespace App\Controllers;

use App\Services\AuthService;
use App\Helpers\Response;

class AuthController
{

    /**
     * Login
     * 
     * @return void
     * 
     * @throws Exception
     */
    public function login()
    {
        $data = json_decode(file_get_contents('php://input'), true);

        if (
            !is_array($data) ||
            !isset($data['username'], $data['password'], $data['license'])
        ) {
            Response::error('MISSING_FIELDS', 400);
        }

        try {
            $service = new AuthService();
            $response = $service->login(
                $data['username'],
                $data['password'],
                $data['license']
            );

            Response::success('Login successful', [
                'token' => $response['token'],
                'expires_in' => $response['expires_in']
            ]);
        } catch (\Exception $e) {
            // Map business errors to HTTP status codes
            $errorMap = [
                'INVALID_CREDENTIALS' => 401,
                'ACCOUNT_LOCKED'      => 423,
                'LICENSE_EXPIRED'     => 403,
                'CLIENT_INACTIVE'     => 403,
                'LICENSE_INACTIVE'    => 403,
                'INVALID_TOKEN'       => 401,
            ];

            $message = $e->getMessage();
            $status  = $errorMap[$message] ?? 400;

            Response::error($message, $status);
        }
    }
}
