<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Services\Admin\AdminUsersLoginService;
use App\Services\ApiClient;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Login admin → token API mobile disimpan di sesi.
 */
class Auth extends BaseController
{
    public function login(): ResponseInterface|string
    {
        if (session()->get('admin_mobile_token')) {
            return redirect()->to(site_url('admin'));
        }

        return view('admin/auth/login');
    }

    public function attempt(): RedirectResponse
    {
        $user = (string) $this->request->getPost('username');
        $pass  = (string) $this->request->getPost('password');

        $client = new ApiClient();
        $res    = $client->postMobile('login', [
            'username' => $user,
            'password' => $pass,
        ]);

        $json = $res['json'];
        if ($res['transport_ok'] && ApiClient::isSuccess($json) && is_array($json) && ! empty($json['token'])) {
            $token    = (string) $json['token'];
            $loginSvc = new AdminUsersLoginService();
            $pid      = $loginSvc->resolvePegawaiIdFromCredentials($user);
            $linked   = ($pid !== null && $pid > 0) ? $loginSvc->findLinkedAdminForPegawaiId($pid) : null;

            if ($linked !== null) {
                $dispUser = $linked['username'] !== '' ? $linked['username'] : $user;
                session()->set([
                    'admin_mobile_token' => $token,
                    'admin_username'     => $dispUser,
                    'admin_auth_source'  => 'admin_users',
                    'admin_ion_user_id'  => $linked['admin_user_id'],
                    'admin_ion_groups'   => $linked['group_names'],
                ]);

                return redirect()->to(site_url('admin'))->with('message', 'Login berhasil (akun admin / grup terhubung).');
            }

            session()->remove(['admin_ion_user_id', 'admin_ion_groups']);
            session()->set([
                'admin_mobile_token' => $token,
                'admin_username'     => $user,
                'admin_auth_source'  => 'pegawai',
            ]);

            return redirect()->to(site_url('admin'))->with('message', 'Login berhasil.');
        }

        $ion = (new AdminUsersLoginService())->tryLogin($user, $pass);
        if (($ion['ok'] ?? false) === true) {
            session()->set([
                'admin_mobile_token' => (string) $ion['token'],
                'admin_username'     => (string) $ion['username'],
                'admin_auth_source'  => 'admin_users',
                'admin_ion_user_id'  => (int) $ion['admin_user_id'],
                'admin_ion_groups'   => $ion['group_names'],
            ]);

            return redirect()->to(site_url('admin'))->with('message', 'Login berhasil (Ion Auth / admin_users).');
        }

        if (($ion['reason'] ?? '') === 'no_group') {
            return redirect()->back()->withInput()->with(
                'error',
                'Akun admin_users tidak memiliki grup di admin_users_groups — login ditolak (sesuai struktur Ion Auth).'
            );
        }

        if (($ion['reason'] ?? '') === 'no_proxy') {
            return redirect()->back()->withInput()->with(
                'error',
                'Akun admin_users valid, tetapi tidak ada pegawai untuk token API. Isi ADMIN_LOGIN_PROXY_PEGAWAI_ID di .env (id_pegawai) atau pastikan tabel pegawai berisi data.'
            );
        }

        $msg = is_array($json) ? (string) ($json['pesan'] ?? 'Login gagal.') : ($res['error'] ?? 'Login gagal.');

        return redirect()->back()->withInput()->with('error', $msg);
    }

    public function logout(): RedirectResponse
    {
        session()->remove([
            'admin_mobile_token',
            'admin_username',
            'admin_auth_source',
            'admin_ion_user_id',
            'admin_ion_groups',
        ]);

        return redirect()->to(site_url('admin/login'))->with('message', 'Anda telah keluar.');
    }
}
