<?php

namespace App\Modules\Auth\Controllers;

use App\Core\BaseApiController;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Auth Controller
 *
 * POST /api/auth/login, POST /api/auth/logout, GET /api/auth/me (session-based).
 */
class AuthController extends BaseApiController
{
    protected AuthService $authService;

    public function __construct()
    {
        $this->authService = new AuthService();
    }

    /**
     * POST /api/auth/login
     * Body: { "email": "", "password": "" }
     */
    public function login(): ResponseInterface
    {
        $input = $this->request->getJSON(true);
        $email = $input['email'] ?? '';
        $password = $input['password'] ?? '';

        if ($email === '' || $password === '') {
            return $this->errorResponse('Email and password are required', null, null, 400);
        }

        $user = $this->authService->login($email, $password);
        if (!$user) {
            return $this->errorResponse('Invalid email or password', null, null, 401);
        }

        return $this->successResponse($user, 'Login successful');
    }

    /**
     * POST /api/auth/logout
     */
    public function logout(): ResponseInterface
    {
        $this->authService->logout();
        return $this->successResponse(null, 'Logged out');
    }

    /**
     * GET /api/auth/me
     */
    public function me(): ResponseInterface
    {
        $user = $this->authService->currentUser();
        if (!$user) {
            return $this->errorResponse('Not authenticated', null, null, 401);
        }
        return $this->successResponse($user, 'Current user');
    }

    /**
     * POST /api/auth/change-password
     * Body: { "current_password": "", "new_password": "" }
     * User can only change their own password.
     */
    public function changePassword(): ResponseInterface
    {
        $user = $this->authService->currentUser();
        if (!$user) {
            return $this->errorResponse('Not authenticated', null, null, 401);
        }

        $input = $this->request->getJSON(true);
        $currentPassword = $input['current_password'] ?? '';
        $newPassword     = $input['new_password'] ?? '';

        if ($currentPassword === '' || $newPassword === '') {
            return $this->errorResponse('Current password and new password are required', null, null, 400);
        }

        if (strlen($newPassword) < 6) {
            return $this->errorResponse('New password must be at least 6 characters', null, null, 400);
        }

        $ok = $this->authService->changePassword(
            (int) $user['id'],
            $currentPassword,
            $newPassword
        );

        if (!$ok) {
            return $this->errorResponse('Current password is incorrect', null, null, 400);
        }

        return $this->successResponse(null, 'Password changed successfully');
    }
}
