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

type Data = {
    error: string
}

type ApiRequest = NextApiRequest & {
    password: (arg: string) => void
}

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: ApiRequest,
    res: NextApiResponse<Data>)
    {
        const data = req.body._data;
        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]) => {
                        
                    })
                })
            }
          );
        /*pool.query(sql[0], [req.login], (err: QueryError, rows: RowDataPacket[0]) => {
            if (rows.length<1) {
                res.status(200).json({error:'Неверный логин'});
                console.log({error:'Неверный логин'});
            } else {
              /*  hashPassword(_data.password, rows[0].salt, function(hash) {
                    pool.query(sql[1], [hash], function(err, rows2) {
                        if (rows2.length == 1) {
                            hashPassword(_data.login+_data.password, rows2[0].salt , function(token) {
                                pool.query(sql[2] [token, rows2[0].id], function() {
                                    res.status(200).json({'token':token});
                                 })
                            });
                        } else {
                            res.status(200).json({error:'Неверный пароль'});
                            console.log({error:'Неверный пароль'});
                        }
                     })
                })
            }
         })*/
    };