import { randomBytes } from 'crypto';
function generateId() {
    return `tm-${Date.now()}-${randomBytes(4).toString('hex')}`;
}
export async function teamRoutes(app, opts) {
    const { db } = opts;
    // GET /api/team — list all team members
    app.get('/api/team', {
        preHandler: [app.requireAuth],
    }, async (_request, reply) => {
        const rows = db.prepare('SELECT * FROM team_members ORDER BY name ASC').all();
        return reply.send({ members: rows });
    });
    // POST /api/team — create a team member
    app.post('/api/team', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { name, role, email, phone } = request.body;
        if (!name?.trim() || !role?.trim()) {
            return reply.status(400).send({ error: 'Name and role are required' });
        }
        const id = generateId();
        const now = new Date().toISOString();
        db.prepare('INSERT INTO team_members (id, name, role, email, phone, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)').run(id, name.trim(), role.trim(), email?.trim() || null, phone?.trim() || null, now, now);
        const member = db.prepare('SELECT * FROM team_members WHERE id = ?').get(id);
        return reply.status(201).send({ member });
    });
    // PATCH /api/team/:id — update a team member
    app.patch('/api/team/:id', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { id } = request.params;
        const existing = db.prepare('SELECT * FROM team_members WHERE id = ?').get(id);
        if (!existing) {
            return reply.status(404).send({ error: 'Team member not found' });
        }
        const { name, role, email, phone } = request.body;
        const now = new Date().toISOString();
        db.prepare('UPDATE team_members SET name = ?, role = ?, email = ?, phone = ?, updated_at = ? WHERE id = ?').run(name?.trim() || existing.name, role?.trim() || existing.role, email !== undefined ? (email?.trim() || null) : existing.email, phone !== undefined ? (phone?.trim() || null) : existing.phone, now, id);
        const member = db.prepare('SELECT * FROM team_members WHERE id = ?').get(id);
        return reply.send({ member });
    });
    // DELETE /api/team/:id — delete a team member
    app.delete('/api/team/:id', {
        preHandler: [app.requireAuth],
    }, async (request, reply) => {
        const { id } = request.params;
        const result = db.prepare('DELETE FROM team_members WHERE id = ?').run(id);
        if (result.changes === 0) {
            return reply.status(404).send({ error: 'Team member not found' });
        }
        return reply.send({ ok: true });
    });
}
//# sourceMappingURL=team-routes.js.map