const bcrypt = require("bcryptjs");
const db = require("../config/db");
const { query } = require("express");

class User {
    static async createUser({ fname, lname, dob, email, password, address, phone}) {
        
        const hashedPassword = await bcrypt.hash(password, 10);

        return new Promise((resolve, reject) => {
            //INSERT ข้อมูลในตาราง user
            db.query(
                "INSERT INTO user (role_id, email, password) VALUES (?, ?, ?)",
                [2, email, hashedPassword],
                (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        const userId = result.insertId; //ดึง user_id ที่เพิ่งถูกเพิ่ม

                        //INSERT ข้อมูลในตาราง patient
                        db.query(
                            "INSERT INTO patient (user_id, fname, lname, phone, dob, address) VALUES (?, ?, ?, ?, ?, ?)",
                            [userId, fname, lname, phone, dob, address],
                            (err, result) => {
                                if (err) {
                                    reject(err);
                                } else {
                                    resolve(result);
                                }
                            }
                        );
                    }
                }
            );
        });
    }
    
    static async findByEmail(email) {
        return new Promise((resolve, reject) => {
            db.query("SELECT * FROM user WHERE email = ?", [email], (err, results) => {
                if (err) reject(err);
                else {
                    console.log(results);
                    resolve(results[0]);
                }
            });
        });
    }
}

module.exports = User;