-- ═══════════════════════════════════════════════════════════════════════
-- 2026-10-28_01 · Solicitud de cotización de venta: prioridad, ofertas
-- requeridas y comentarios / cambios pedidos sobre una oferta
-- ═══════════════════════════════════════════════════════════════════════
-- · prioridad: baja | media | alta | urgente. Define con cuánta anticipación
--   a la fecha en que el cliente lo necesita se recuerda la entrega
--   (TareasDiarias::avisosCotizacionesPorEntregar).
-- · ofertas_requeridas: cuántas ofertas quiere Ventas para el cliente (≥ 1).
--   La solicitud pasa a "presupuestada" (y se avisa a Ventas) cuando hay al
--   menos esa cantidad de ofertas listas.
-- · Oferta en estado "cambios": Ventas pidió un ajuste; vuelve al cotizador
--   y regresa a "lista" cuando él la termina de nuevo.
-- · cotizacion_venta_oferta_comentario: hilo de comentarios por oferta entre
--   Ventas y el cotizador; pide_cambio marca los que exigen un ajuste.
--
-- Respaldo: backups/tinsa_db_pre-prioridad-cotizacion_2026-10-28.sql
-- Reversa:  database/rollback/2026-10-28_01_prioridad_ofertas_cotizacion.down.sql
-- ═══════════════════════════════════════════════════════════════════════

USE tinsa_db;

ALTER TABLE cotizacion_venta
  ADD COLUMN prioridad ENUM('baja','media','alta','urgente') NOT NULL DEFAULT 'media' AFTER fecha_necesidad,
  ADD COLUMN ofertas_requeridas TINYINT UNSIGNED NOT NULL DEFAULT 1 AFTER prioridad;

ALTER TABLE cotizacion_venta_oferta
  MODIFY estado ENUM('borrador','lista','cambios','seleccionada','descartada') NOT NULL DEFAULT 'borrador';

CREATE TABLE cotizacion_venta_oferta_comentario (
  id           INT UNSIGNED NOT NULL AUTO_INCREMENT,
  id_oferta    INT UNSIGNED NOT NULL,
  origen       ENUM('ventas','presupuesto') NOT NULL,
  texto        TEXT NOT NULL,
  pide_cambio  TINYINT(1) NOT NULL DEFAULT 0,
  atendido_en  DATETIME NULL COMMENT 'cuando el cotizador volvió a terminar la oferta',
  id_usuario   INT UNSIGNED NULL,
  created_at   TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_cvoc_oferta (id_oferta),
  CONSTRAINT fk_cvoc_oferta FOREIGN KEY (id_oferta) REFERENCES cotizacion_venta_oferta (id) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT fk_cvoc_usuario FOREIGN KEY (id_usuario) REFERENCES usuarios (id_usuario) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
