const db = require('../config/db'); class TicketVisita { static async create(data) { const { company_id, ticket_id, external_id = null, tecnico_email, tecnico_nombre = null, titulo, descripcion = null, ubicacion = null, latitud = null, longitud = null, fecha_visita = null, fecha_fin = null, estado = 'programada', checklist_json = null, historial_json = null } = data; const [result] = await db.query( `INSERT INTO ticket_visitas (company_id, ticket_id, external_id, tecnico_email, tecnico_nombre, titulo, descripcion, ubicacion, latitud, longitud, fecha_visita, fecha_fin, estado, checklist_json, historial_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ company_id, ticket_id, external_id, tecnico_email, tecnico_nombre, titulo, descripcion, ubicacion, latitud, longitud, fecha_visita, fecha_fin, estado, typeof checklist_json === 'object' && checklist_json !== null ? JSON.stringify(checklist_json) : checklist_json, typeof historial_json === 'object' && historial_json !== null ? JSON.stringify(historial_json) : historial_json ] ); return result.insertId; } static async findByTicket(companyId, ticketId) { const [rows] = await db.query( 'SELECT * FROM ticket_visitas WHERE company_id = ? AND ticket_id = ? ORDER BY id DESC LIMIT 1', [companyId, ticketId] ); return rows[0] || null; } static async findAllByTicket(companyId, ticketId) { const [rows] = await db.query( 'SELECT * FROM ticket_visitas WHERE company_id = ? AND ticket_id = ? ORDER BY id DESC', [companyId, ticketId] ); return rows; } static async findById(id) { const [rows] = await db.query('SELECT * FROM ticket_visitas WHERE id = ?', [id]); return rows[0] || null; } static async update(id, data) { const fields = []; const values = []; for (const [key, val] of Object.entries(data)) { fields.push(`${key} = ?`); if ((key === 'checklist_json' || key === 'historial_json') && typeof val === 'object' && val !== null) { values.push(JSON.stringify(val)); } else { values.push(val); } } if (fields.length === 0) return; values.push(id); await db.query(`UPDATE ticket_visitas SET ${fields.join(', ')} WHERE id = ?`, values); } } module.exports = TicketVisita;