// src/routes/register/+server.ts
import type { RequestHandler } from './$types';
import { json } from '@sveltejs/kit';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import pool from '$lib/server/database';
import { JWT_SECRET } from '$env/static/private';

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

		if (!workerName || !login_id || !password)
			return json({ error: '모든 항목을 입력하세요.' }, { status: 400 });

		if (login_id.toLowerCase().includes('admin'))
			return json({ error: '관리자 전용 아이디는 등록할 수 없습니다.' }, { status: 403 });

		//if (password.length < 8 || !/[0-9]/.test(password) || !/[A-Za-z]/.test(password))
		//	return json({ error: '비밀번호는 8자 이상이며 숫자와 문자를 포함해야 합니다.' }, { status: 400 });

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

		const result = await pool.query(
			`INSERT INTO "Worker" (WorkerName, login_id, password_hash)
			 VALUES ($1, $2, $3)
			 RETURNING WorkerID`,
			[workerName, login_id, hashedPassword]
		);

		const worker = { id: result.rows[0].workerid, login_id, name: workerName };

		const token = jwt.sign(worker, JWT_SECRET, { expiresIn: '7d' });
		cookies.set('session', token, {
			path: '/',
			httpOnly: true,
			secure: false,
			maxAge: 60 * 60 * 24 * 7
		});

		return json({ success: true, worker });
	} catch (err: any) {
		console.error('회원 등록 실패:', err);
		if (err.code === '23505')
			return json({ error: '이미 사용 중인 아이디입니다.' }, { status: 400 });
		return json({ error: '서버 오류' }, { status: 500 });
	}
};
