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

const router = Router();

// ── Row mappers ───────────────────────────────────────────────────────────────

const toMachine = (m: Record<string, unknown>) => ({
  id:             m.id,
  serialNumber:   m.serial_number,
  purchaseDate:   m.purchase_date,
  warrantyExpiry: m.warranty_expiry,
  ...(m.color    && { color:    m.color }),
  ...(m.notes    && { notes:    m.notes }),
  ...(m.location && { location: m.location }),
});

const toCustomer = (r: Record<string, unknown>, machines: Record<string, unknown>[]) => ({
  id:        r.id,
  name:      r.name,
  phone:     r.phone,
  createdAt: r.created_at,
  ...(r.email   && { email:   r.email }),
  ...(r.address && { address: r.address }),
  ...(r.line_id && { lineId:  r.line_id }),
  machines: machines
    .filter(m => m.customer_id === r.id)
    .map(toMachine),
});

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

// GET /api/customers
router.get('/', async (_req, res) => {
  try {
    const [c, m] = await Promise.all([
      pool.query('SELECT * FROM simo_customers ORDER BY created_at DESC'),
      pool.query('SELECT * FROM simo_machines ORDER BY purchase_date ASC'),
    ]);
    res.json(c.rows.map(r => toCustomer(r, m.rows)));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// GET /api/customers/:id
router.get('/:id', async (req, res) => {
  try {
    const [c, m] = await Promise.all([
      pool.query('SELECT * FROM simo_customers WHERE id = $1', [req.params.id]),
      pool.query('SELECT * FROM simo_machines WHERE customer_id = $1 ORDER BY purchase_date ASC', [req.params.id]),
    ]);
    if (!c.rows.length) return res.status(404).json({ error: 'Not found' });
    res.json(toCustomer(c.rows[0], m.rows.map(r => ({ ...r, customer_id: req.params.id }))));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// POST /api/customers
router.post('/', async (req, res) => {
  const { name, phone, email, address, lineId, createdAt } = req.body;
  try {
    const passwordHash = await bcrypt.hash('1234', 10);
    const r = await pool.query(
      `INSERT INTO simo_customers (name, phone, email, address, line_id, created_at, password_hash)
       VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
      [name, phone, email ?? null, address ?? null, lineId ?? null, createdAt ?? new Date().toISOString(), passwordHash],
    );
    res.status(201).json(toCustomer(r.rows[0], []));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// PUT /api/customers/:id
router.put('/:id', async (req, res) => {
  const { name, phone, email, address, lineId } = req.body;
  try {
    await pool.query(
      `UPDATE simo_customers SET name=$1,phone=$2,email=$3,address=$4,line_id=$5 WHERE id=$6`,
      [name, phone, email ?? null, address ?? null, lineId ?? null, req.params.id],
    );
    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// DELETE /api/customers/:id
router.delete('/:id', async (req, res) => {
  try {
    await pool.query('DELETE FROM simo_customers WHERE id=$1', [req.params.id]);
    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// POST /api/customers/:id/machines
router.post('/:id/machines', async (req, res) => {
  const { serialNumber, purchaseDate, warrantyExpiry, color, notes, location } = req.body;
  try {
    const r = await pool.query(
      `INSERT INTO simo_machines (customer_id,serial_number,purchase_date,warranty_expiry,color,notes,location)
       VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
      [req.params.id, serialNumber, purchaseDate, warrantyExpiry, color ?? null, notes ?? null, location ?? null],
    );
    res.status(201).json(toMachine(r.rows[0]));
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// PUT /api/customers/:id/machines/:mid
router.put('/:id/machines/:mid', async (req, res) => {
  const { serialNumber, purchaseDate, warrantyExpiry, color, notes, location } = req.body;
  try {
    await pool.query(
      `UPDATE simo_machines SET serial_number=$1,purchase_date=$2,warranty_expiry=$3,color=$4,notes=$5,location=$6
       WHERE id=$7 AND customer_id=$8`,
      [serialNumber, purchaseDate, warrantyExpiry, color ?? null, notes ?? null, location ?? null, req.params.mid, req.params.id],
    );
    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

// DELETE /api/customers/:id/machines/:mid
router.delete('/:id/machines/:mid', async (req, res) => {
  try {
    await pool.query('DELETE FROM simo_machines WHERE id=$1 AND customer_id=$2', [req.params.mid, req.params.id]);
    res.json({ ok: true });
  } catch (e) { res.status(500).json({ error: String(e) }); }
});

export default router;
