const express = require('express'); const router = express.Router(); const { getDb } = require('../db'); router.get('/', (req, res) => { try { const db = getDb(); const rows = db.prepare('SELECT * FROM customers ORDER BY name').all(); res.json(rows); } catch (err) { res.status(500).json({ error: err.message }); } }); router.get('/:id', (req, res) => { try { const db = getDb(); const row = db.prepare('SELECT * FROM customers WHERE id = ?').get(req.params.id); if (!row) return res.status(404).json({ error: 'Customer not found' }); res.json(row); } catch (err) { res.status(500).json({ error: err.message }); } }); router.post('/', (req, res) => { try { const db = getDb(); const { name, phone, email, address, notes } = req.body; if (!name || name.trim() === '') { return res.status(400).json({ error: 'Name is required' }); } const result = db.prepare( 'INSERT INTO customers (name, phone, email, address, notes) VALUES (?, ?, ?, ?, ?)' ).run( name.trim(), phone ? String(phone).trim() : null, email ? String(email).trim() : null, address ? String(address).trim() : null, notes ? String(notes).trim() : null ); const row = db.prepare('SELECT * FROM customers WHERE id = ?').get(result.lastInsertRowid); res.status(201).json(row); } catch (err) { res.status(500).json({ error: err.message }); } }); router.put('/:id', (req, res) => { try { const db = getDb(); const existing = db.prepare('SELECT * FROM customers WHERE id = ?').get(req.params.id); if (!existing) return res.status(404).json({ error: 'Customer not found' }); const { name, phone, email, address, notes } = req.body; const n = name !== undefined ? name.trim() : existing.name; const ph = phone !== undefined ? (phone ? String(phone).trim() : null) : existing.phone; const e = email !== undefined ? (email ? String(email).trim() : null) : existing.email; const a = address !== undefined ? (address ? String(address).trim() : null) : existing.address; const no = notes !== undefined ? (notes ? String(notes).trim() : null) : existing.notes; if (!n) return res.status(400).json({ error: 'Name is required' }); db.prepare( 'UPDATE customers SET name = ?, phone = ?, email = ?, address = ?, notes = ? WHERE id = ?' ).run(n, ph, e, a, no, req.params.id); const row = db.prepare('SELECT * FROM customers WHERE id = ?').get(req.params.id); res.json(row); } catch (err) { res.status(500).json({ error: err.message }); } }); router.delete('/:id', (req, res) => { try { const db = getDb(); const result = db.prepare('DELETE FROM customers WHERE id = ?').run(req.params.id); if (result.changes === 0) return res.status(404).json({ error: 'Customer not found' }); res.status(204).send(); } catch (err) { res.status(500).json({ error: err.message }); } }); module.exports = router;