import { Express, Request} from 'express';
import {Keycloak} from 'keycloak-connect';
import {ResponseWrapper} from '../dom'
import { LoginRes, LoginSession } from './route-login-session';

export const routeLogin = (app: Express, keycloak: Keycloak ) => {
    app.post('/login', async (req: Request<LoginRes, ResponseWrapper<LoginSession>, LoginRes>, res) => {
    
        try {
            if (!req.body.username || !req.body.password) {
                return res.status(400).json({error: 'Username and password are required'});
            }
    
            const grant = await keycloak.grantManager.obtainDirectly(
                req.body.username,
                req.body.password,
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore какая-то глючная типизация у клояки, уверенности что параметр вообще нужен нет
                'openid',
            );
    
            keycloak.storeGrant(grant, req, res);
            res.json({
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore глючные типы 
                // eslint-disable-next-line max-len
                // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
                token_type: grant.access_token?.content?.typ || 'Bearer',
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore глючные типы 
                // eslint-disable-next-line max-len
                // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
                expires_in: grant.access_token?.content.exp,
                scope: 'openid',
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore глючные типы 
                // eslint-disable-next-line max-len
                // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
                access_token: grant.access_token?.token,
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore глючные типы 
                // eslint-disable-next-line max-len
                // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
                refresh_token: grant.refresh_token?.token,
            });
        } catch (err) {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            //@ts-ignore
            // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
            console.error('Login failed:', err?.response?.data || err?.message || err);
            res.status(401).json({error: 'invalid_credentials'});
        }
    });
}