import { Router } from 'express';
import bcrypt from 'bcrypt';
import { pool } from '../db';

const router = Router();

const SALT_ROUNDS = 10;

const normalize  = (phone: string) => phone.replace(/[-\s]/g, '');
const toMsisdn   = (phone: string) =>
  phone.startsWith('0') ? '66' + phone.slice(1) : phone;

// ── ThaiBulkSMS OTP ───────────────────────────────────────────────────────────

const tbsKey    = () => process.env.THAIBULKSMS_KEY    ?? '';
const tbsSecret = () => process.env.THAIBULKSMS_SECRET ?? '';

async function tbsRequest(phone: string): Promise<string> {
  const body = new URLSearchParams({
    key:    tbsKey(),
    secret: tbsSecret(),
    msisdn: toMsisdn(phone),
  });
  const res  = await fetch('https://otp.thaibulksms.com/v2/otp/request', {
    method:  'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body:    body.toString(),
  });
  const json = await res.json() as { token?: string; code?: string };
  if (!json.token) throw new Error(`ThaiBulkSMS request failed: ${JSON.stringify(json)}`);
  return json.token;
}

async function tbsVerify(token: string, pin: string): Promise<boolean> {
  const body = new URLSearchParams({
    key:    tbsKey(),
    secret: tbsSecret(),
    token,
    pin,
  });
  const res  = await fetch('https://otp.thaibulksms.com/v2/otp/verify', {
    method:  'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body:    body.toString(),
  });
  const json = await res.json() as { status?: string; code?: number };
  return json.status === 'success';
}

// ── Routes ────────────────────────────────────────────────────────────────────

// POST /api/auth/customer/login
router.post('/customer/login', async (req, res) => {
  const { phone, password } = req.body as { phone: string; password: string };
  if (!phone || !password) return res.status(400).json({ error: 'กรุณากรอกเบอร์โทรและรหัสผ่าน' });

  try {
    const n = normalize(phone);
    const { rows } = await pool.query('SELECT * FROM simo_customers WHERE phone = $1', [n]);
    if (!rows.length) return res.status(401).json({ error: 'ไม่พบเบอร์โทรในระบบ' });

    const c = rows[0];
    let ok: boolean;

    if (!c.password_hash) {
      ok = password === '1234';
      if (ok) {
        const hash = await bcrypt.hash('1234', SALT_ROUNDS);
        await pool.query('UPDATE simo_customers SET password_hash=$1 WHERE id=$2', [hash, c.id]);
      }
    } else {
      ok = await bcrypt.compare(password, c.password_hash as string);
    }

    if (!ok) return res.status(401).json({ error: 'รหัสผ่านไม่ถูกต้อง' });

    res.json({ id: c.id, name: c.name, phone: c.phone, role: 'customer' });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// POST /api/auth/customer/request-otp
// ThaiBulkSMS ส่ง SMS และคืน token — เราเก็บ token ไว้ใน DB
router.post('/customer/request-otp', async (req, res) => {
  const { phone } = req.body as { phone: string };
  if (!phone) return res.status(400).json({ error: 'กรุณากรอกเบอร์โทร' });

  try {
    const n = normalize(phone);
    const { rows } = await pool.query('SELECT id FROM simo_customers WHERE phone = $1', [n]);
    if (!rows.length) return res.status(404).json({ error: 'ไม่พบเบอร์โทรในระบบ' });

    const customerId = rows[0].id;

    const token = await tbsRequest(n);

    // ยกเลิก token เก่า แล้วเก็บ token ใหม่
    await pool.query('UPDATE simo_otps SET used=TRUE WHERE customer_id=$1 AND used=FALSE', [customerId]);
    await pool.query(
      `INSERT INTO simo_otps (customer_id, otp_code, expires_at)
       VALUES ($1, $2, NOW() + INTERVAL '5 minutes')`,
      [customerId, token],
    );

    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// POST /api/auth/customer/change-password
// รับ pin ที่ลูกค้าได้รับทาง SMS ยืนยันกับ ThaiBulkSMS แล้วเปลี่ยน password
router.post('/customer/change-password', async (req, res) => {
  const { phone, otp: pin, newPassword } = req.body as { phone: string; otp: string; newPassword: string };
  if (!phone || !pin || !newPassword) return res.status(400).json({ error: 'ข้อมูลไม่ครบ' });
  if (newPassword.length < 6) return res.status(400).json({ error: 'รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร' });

  try {
    const n = normalize(phone);
    const { rows } = await pool.query('SELECT id FROM simo_customers WHERE phone = $1', [n]);
    if (!rows.length) return res.status(404).json({ error: 'ไม่พบเบอร์โทร' });

    const customerId = rows[0].id;
    const tokenRow   = await pool.query(
      `SELECT id, otp_code FROM simo_otps
       WHERE customer_id=$1 AND used=FALSE AND expires_at > NOW()
       ORDER BY created_at DESC LIMIT 1`,
      [customerId],
    );
    if (!tokenRow.rows.length) return res.status(400).json({ error: 'กรุณาขอ OTP ใหม่' });

    const token = tokenRow.rows[0].otp_code as string;
    const valid = await tbsVerify(token, pin);
    if (!valid) return res.status(400).json({ error: 'รหัส OTP ไม่ถูกต้อง' });

    await pool.query('UPDATE simo_otps SET used=TRUE WHERE id=$1', [tokenRow.rows[0].id]);

    const hash = await bcrypt.hash(newPassword, SALT_ROUNDS);
    await pool.query('UPDATE simo_customers SET password_hash=$1 WHERE id=$2', [hash, customerId]);

    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

export default router;
