const express = require('express');
const router = express.Router();
const Admin = require('../models/Admin');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// Login Admin
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    const admin = await Admin.findOne({ where: { username } });
    if (!admin) return res.status(400).json({ error: 'Username atau password salah' });

    const validPassword = await bcrypt.compare(password, admin.password_hash);
    if (!validPassword) return res.status(400).json({ error: 'Username atau password salah' });

    const token = jwt.sign({ id: admin.id, username: admin.username }, process.env.JWT_SECRET, { expiresIn: '1d' });
    res.json({ token, username: admin.username });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Setup Init Admin (Hanya untuk testing, hapus kalau sudah prod)
router.post('/setup', async (req, res) => {
  try {
     const existingAdmin = await Admin.findOne();
     if (existingAdmin) return res.status(400).json({ error: 'Admin sudah ada.' });

     const salt = await bcrypt.genSalt(10);
     const password_hash = await bcrypt.hash('admin123', salt);

     const newAdmin = await Admin.create({ username: 'admin', password_hash });
     res.json({ message: 'Admin dibuat dengan password default: admin123', admin: { username: newAdmin.username } });
  } catch(error) {
     res.status(500).json({ error: error.message });
  }
});

module.exports = router;
