import type { RequestHandler } from './$types';
import { json, error } from '@sveltejs/kit';
import bcrypt from 'bcrypt';
import pool from '$lib/server/database';

export const POST: RequestHandler = async ({ request }) => {
	const { login_id, password, worker_name } = await request.json();

	if (!login_id || !password || !worker_name)
		throw error(400, '모든 필드를 입력해주세요.');

	const salt = await bcrypt.genSalt(10);
	const hash = await bcrypt.hash(password, salt);

	try {
		await pool.query(
			'INSERT INTO "Worker" (WorkerName, login_id, password_hash) VALUES ($1, $2, $3)',
			[worker_name, login_id, hash]
		);
		return json({ message: '작업자 등록 완료' });
	} catch (err: any) {
		throw error(500, '이미 존재하는 로그인 아이디거나 DB 오류입니다.');
	}
};
