// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { RowDataPacket } from "mysql2";
import type { NextApiRequest, NextApiResponse } from 'next';
import { pool } from "../../../server/db/connect";
import { HashPassword } from '../../../components/admin/function/hashPassword'

const sql = ["SELECT salt FROM user WHERE login=?",
             "SELECT salt, id FROM user WHERE password_hash=?",
             "UPDATE user SET token = ? WHERE id = ?"];

export default function handler(
    req: NextApiRequest,
    res: NextApiResponse)
    {
        const data = req.body.params;
        req.method === 'POST' ?
        pool.query( sql[0], [data.login], (err, result:RowDataPacket[0]) => {
              if (err) {console.log(err)};
              !result.length ?
                res.status(200).json({error:'Неверный логин'}) :
                    HashPassword(data.password, result[0].salt, function(hash) {
                        pool.query(sql[1], [hash], (err, result:RowDataPacket[0]) => {
                            if (err) {console.log(err)};
                            result.length ?
                                HashPassword(data.login+data.password+new Date().toISOString(), result[0].salt , function(token) {
                                    pool.query(sql[2], [token, result[0].id], function() {
                                        res.status(200).json({token:token});
                                    })
                                }) : res.status(200).json({error:'Неверный пароль'})
                    })
                })
            }
          ) : res.status(200).json('null');
    };