SET NAMES utf8mb4;
SET time_zone = '-06:00';

CREATE TABLE IF NOT EXISTS planes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(60) NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  max_sucursales INT UNSIGNED NOT NULL DEFAULT 1,
  max_cajas INT UNSIGNED NOT NULL DEFAULT 1,
  configuracion_json LONGTEXT NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_planes_codigo (codigo),
  KEY idx_planes_estado (estado)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS categorias_gastronomicas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(60) NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  configuracion_json LONGTEXT NOT NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_categoria_codigo (codigo),
  KEY idx_categoria_estado (estado)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS negocios (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  plan_id BIGINT UNSIGNED NULL,
  categoria_gastronomica_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  nombre_comercial VARCHAR(120) NULL,
  tipo_identificacion CHAR(2) NULL,
  identificacion VARCHAR(20) NULL,
  codigo_actividad VARCHAR(6) NULL,
  correo VARCHAR(160) NULL,
  telefono_codigo_pais VARCHAR(3) NOT NULL DEFAULT '506',
  telefono VARCHAR(20) NULL,
  moneda_base CHAR(3) NOT NULL DEFAULT 'CRC',
  usa_facturacion TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activo','suspendido','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_negocios_plan (plan_id),
  KEY idx_negocios_categoria (categoria_gastronomica_id),
  KEY idx_negocios_identificacion (tipo_identificacion, identificacion),
  KEY idx_negocios_estado (estado),
  CONSTRAINT fk_negocios_plan FOREIGN KEY (plan_id) REFERENCES planes(id),
  CONSTRAINT fk_negocios_categoria FOREIGN KEY (categoria_gastronomica_id) REFERENCES categorias_gastronomicas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sucursales (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  codigo_interno VARCHAR(20) NOT NULL DEFAULT 'principal',
  codigo_fiscal CHAR(3) NOT NULL DEFAULT '001',
  provincia CHAR(1) NULL,
  canton CHAR(2) NULL,
  distrito CHAR(2) NULL,
  barrio VARCHAR(50) NULL,
  otras_sennas VARCHAR(250) NULL,
  correo VARCHAR(160) NULL,
  telefono_codigo_pais VARCHAR(3) NOT NULL DEFAULT '506',
  telefono VARCHAR(20) NULL,
  es_principal TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activa','inactiva','suspendida') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_sucursal_codigo_fiscal (negocio_id, codigo_fiscal),
  KEY idx_sucursales_negocio_estado (negocio_id, estado),
  KEY idx_sucursales_ubicacion (provincia, canton, distrito),
  CONSTRAINT fk_sucursales_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS roles (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(60) NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  alcance ENUM('plataforma','negocio','sucursal') NOT NULL DEFAULT 'negocio',
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  PRIMARY KEY (id),
  UNIQUE KEY uq_roles_codigo (codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS permisos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  codigo VARCHAR(100) NOT NULL,
  nombre VARCHAR(140) NOT NULL,
  modulo VARCHAR(80) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_permisos_codigo (codigo),
  KEY idx_permisos_modulo (modulo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rol_permisos (
  rol_id BIGINT UNSIGNED NOT NULL,
  permiso_id BIGINT UNSIGNED NOT NULL,
  PRIMARY KEY (rol_id, permiso_id),
  CONSTRAINT fk_rp_rol FOREIGN KEY (rol_id) REFERENCES roles(id),
  CONSTRAINT fk_rp_permiso FOREIGN KEY (permiso_id) REFERENCES permisos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS usuarios (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  rol_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(160) NOT NULL,
  correo VARCHAR(180) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  estado ENUM('activo','suspendido','inactivo') NOT NULL DEFAULT 'activo',
  ultimo_acceso_at DATETIME NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_usuarios_correo (correo),
  KEY idx_usuarios_negocio_estado (negocio_id, estado),
  KEY idx_usuarios_sucursal (negocio_id, sucursal_id),
  KEY idx_usuarios_rol (rol_id),
  CONSTRAINT fk_usuarios_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_usuarios_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_usuarios_rol FOREIGN KEY (rol_id) REFERENCES roles(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE IF NOT EXISTS cajas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(120) NOT NULL,
  codigo_terminal CHAR(5) NULL,
  licencia_codigo VARCHAR(80) NULL,
  emite_factura TINYINT(1) NOT NULL DEFAULT 0,
  estado ENUM('activa','inactiva','bloqueada') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_cajas_sucursal_estado (negocio_id, sucursal_id, estado),
  KEY idx_cajas_terminal (negocio_id, sucursal_id, codigo_terminal),
  CONSTRAINT fk_cajas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cajas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS caja_sesiones (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NOT NULL,
  usuario_id BIGINT UNSIGNED NOT NULL,
  monto_inicial DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_efectivo_sistema DECIMAL(18,5) NOT NULL DEFAULT 0,
  monto_efectivo_contado DECIMAL(18,5) NOT NULL DEFAULT 0,
  diferencia_cierre DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_ventas DECIMAL(18,5) NOT NULL DEFAULT 0,
  estado ENUM('abierta','cerrada','anulada') NOT NULL DEFAULT 'abierta',
  abierta_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  cerrada_at DATETIME NULL,
  observacion VARCHAR(255) NULL,
  PRIMARY KEY (id),
  KEY idx_caja_sesiones_abierta (negocio_id, sucursal_id, caja_id, estado),
  KEY idx_caja_sesiones_usuario (usuario_id, estado),
  CONSTRAINT fk_cs_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_cs_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_cs_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_cs_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS areas_restaurante (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(100) NOT NULL,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  PRIMARY KEY (id),
  KEY idx_areas_sucursal (negocio_id, sucursal_id, estado, orden),
  CONSTRAINT fk_areas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_areas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mesas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  area_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(40) NOT NULL,
  capacidad SMALLINT UNSIGNED NOT NULL DEFAULT 4,
  estado ENUM('LIBRE','OCUPADA','EN_COCINA','LISTA','EN_COBRO','RESERVADA','CERRADA','BLOQUEADA') NOT NULL DEFAULT 'LIBRE',
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  PRIMARY KEY (id),
  KEY idx_mesas_mapa (negocio_id, sucursal_id, area_id, estado, orden),
  CONSTRAINT fk_mesas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_mesas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_mesas_area FOREIGN KEY (area_id) REFERENCES areas_restaurante(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS clientes (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  nombre VARCHAR(160) NOT NULL,
  nombre_comercial VARCHAR(100) NULL,
  tipo_identificacion CHAR(2) NULL,
  identificacion VARCHAR(20) NULL,
  codigo_actividad VARCHAR(6) NULL,
  correo VARCHAR(160) NULL,
  telefono_codigo_pais VARCHAR(3) NOT NULL DEFAULT '506',
  telefono VARCHAR(20) NULL,
  provincia CHAR(1) NULL,
  canton CHAR(2) NULL,
  distrito CHAR(2) NULL,
  barrio VARCHAR(50) NULL,
  otras_sennas VARCHAR(160) NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_clientes_negocio_nombre (negocio_id, nombre),
  KEY idx_clientes_identificacion (negocio_id, tipo_identificacion, identificacion),
  KEY idx_clientes_correo (negocio_id, correo),
  CONSTRAINT fk_clientes_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_clientes_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS productos_categorias (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  nombre VARCHAR(120) NOT NULL,
  orden SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  PRIMARY KEY (id),
  KEY idx_prod_cat_negocio (negocio_id, sucursal_id, estado, orden),
  CONSTRAINT fk_prod_cat_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_prod_cat_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS areas_produccion (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  nombre VARCHAR(100) NOT NULL,
  impresora_nombre VARCHAR(120) NULL,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  PRIMARY KEY (id),
  KEY idx_area_prod_negocio (negocio_id, sucursal_id, estado),
  CONSTRAINT fk_area_prod_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_area_prod_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS productos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  categoria_id BIGINT UNSIGNED NULL,
  area_produccion_id BIGINT UNSIGNED NULL,
  tipo ENUM('producto_final','materia_prima','insumo_consumo','combo','servicio','reventa','preparado') NOT NULL DEFAULT 'producto_final',
  nombre VARCHAR(180) NOT NULL,
  codigo_interno VARCHAR(60) NULL,
  codigo_barras VARCHAR(80) NULL,
  codigo_cabys VARCHAR(13) NULL,
  unidad_medida VARCHAR(15) NOT NULL DEFAULT 'Unid',
  precio DECIMAL(18,5) NOT NULL DEFAULT 0,
  costo_promedio DECIMAL(18,5) NOT NULL DEFAULT 0,
  codigo_impuesto CHAR(2) NOT NULL DEFAULT '01',
  codigo_tarifa_iva CHAR(2) NULL DEFAULT '08',
  tarifa_iva DECIMAL(5,2) NOT NULL DEFAULT 13.00,
  permite_modificadores TINYINT(1) NOT NULL DEFAULT 0,
  permite_notas TINYINT(1) NOT NULL DEFAULT 1,
  afecta_inventario TINYINT(1) NOT NULL DEFAULT 1,
  imagen_path VARCHAR(255) NULL,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_productos_busqueda (negocio_id, sucursal_id, estado, nombre),
  KEY idx_productos_categoria (negocio_id, categoria_id, estado),
  KEY idx_productos_cabys (codigo_cabys),
  KEY idx_productos_codigo_barras (negocio_id, codigo_barras),
  CONSTRAINT fk_productos_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_productos_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_productos_categoria FOREIGN KEY (categoria_id) REFERENCES productos_categorias(id),
  CONSTRAINT fk_productos_area_prod FOREIGN KEY (area_produccion_id) REFERENCES areas_produccion(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS ventas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  caja_id BIGINT UNSIGNED NULL,
  caja_sesion_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NOT NULL,
  cliente_id BIGINT UNSIGNED NULL,
  origen ENUM('pos','mesa','barra','delivery','para_llevar','catalogo') NOT NULL DEFAULT 'pos',
  numero VARCHAR(40) NOT NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  tipo_cambio DECIMAL(18,5) NOT NULL DEFAULT 1,
  subtotal DECIMAL(18,5) NOT NULL DEFAULT 0,
  descuento_total DECIMAL(18,5) NOT NULL DEFAULT 0,
  servicio_10 DECIMAL(18,5) NOT NULL DEFAULT 0,
  impuesto_total DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL DEFAULT 0,
  estado ENUM('borrador','abierta','cobrada','facturada','anulada') NOT NULL DEFAULT 'borrador',
  idempotency_key VARCHAR(120) NULL,
  creada_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  cobrada_at DATETIME NULL,
  facturada_at DATETIME NULL,
  actualizada_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_ventas_numero (negocio_id, numero),
  UNIQUE KEY uq_ventas_idempotency (negocio_id, idempotency_key),
  KEY idx_ventas_negocio_fecha (negocio_id, creada_at),
  KEY idx_ventas_sucursal_fecha (negocio_id, sucursal_id, creada_at),
  KEY idx_ventas_estado (negocio_id, estado, creada_at),
  KEY idx_ventas_caja (negocio_id, sucursal_id, caja_id, creada_at),
  CONSTRAINT fk_ventas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_ventas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_ventas_caja FOREIGN KEY (caja_id) REFERENCES cajas(id),
  CONSTRAINT fk_ventas_sesion FOREIGN KEY (caja_sesion_id) REFERENCES caja_sesiones(id),
  CONSTRAINT fk_ventas_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id),
  CONSTRAINT fk_ventas_cliente FOREIGN KEY (cliente_id) REFERENCES clientes(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS venta_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  venta_id BIGINT UNSIGNED NOT NULL,
  negocio_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  numero_linea INT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  detalle VARCHAR(200) NOT NULL,
  precio_unitario DECIMAL(18,5) NOT NULL,
  descuento DECIMAL(18,5) NOT NULL DEFAULT 0,
  sub_total DECIMAL(18,5) NOT NULL,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total_linea DECIMAL(18,5) NOT NULL,
  notas VARCHAR(255) NULL,
  modificadores_json LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_venta_lineas_venta (venta_id),
  KEY idx_venta_lineas_producto (negocio_id, producto_id, creado_at),
  CONSTRAINT fk_vl_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_vl_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_vl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS venta_pagos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  venta_id BIGINT UNSIGNED NOT NULL,
  negocio_id BIGINT UNSIGNED NOT NULL,
  medio_pago CHAR(2) NOT NULL,
  medio_pago_otro VARCHAR(100) NULL,
  moneda CHAR(3) NOT NULL DEFAULT 'CRC',
  monto DECIMAL(18,5) NOT NULL,
  referencia VARCHAR(120) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_venta_pagos_venta (venta_id),
  KEY idx_venta_pagos_medio (negocio_id, medio_pago, creado_at),
  CONSTRAINT fk_vp_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_vp_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mesa_cuentas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  mesa_id BIGINT UNSIGNED NOT NULL,
  mesero_id BIGINT UNSIGNED NULL,
  venta_id BIGINT UNSIGNED NULL,
  estado ENUM('abierta','en_cocina','lista','en_cobro','cerrada','anulada') NOT NULL DEFAULT 'abierta',
  comensales SMALLINT UNSIGNED NOT NULL DEFAULT 1,
  total_actual DECIMAL(18,5) NOT NULL DEFAULT 0,
  abierta_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  cerrada_at DATETIME NULL,
  PRIMARY KEY (id),
  KEY idx_mesa_cuentas_abiertas (negocio_id, sucursal_id, estado, mesa_id),
  KEY idx_mesa_cuentas_mesero (negocio_id, sucursal_id, mesero_id, estado),
  CONSTRAINT fk_mc_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_mc_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_mc_mesa FOREIGN KEY (mesa_id) REFERENCES mesas(id),
  CONSTRAINT fk_mc_mesero FOREIGN KEY (mesero_id) REFERENCES usuarios(id),
  CONSTRAINT fk_mc_venta FOREIGN KEY (venta_id) REFERENCES ventas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS mesa_cuenta_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  cuenta_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  precio_unitario DECIMAL(18,5) NOT NULL,
  impuesto DECIMAL(18,5) NOT NULL DEFAULT 0,
  total DECIMAL(18,5) NOT NULL,
  comensal_numero SMALLINT UNSIGNED NULL,
  estado_comanda ENUM('pendiente','enviada','preparando','lista','entregada','cancelada') NOT NULL DEFAULT 'pendiente',
  notas VARCHAR(255) NULL,
  modificadores_json LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_mcl_cuenta (cuenta_id),
  KEY idx_mcl_producto (producto_id),
  KEY idx_mcl_estado_comanda (estado_comanda),
  CONSTRAINT fk_mcl_cuenta FOREIGN KEY (cuenta_id) REFERENCES mesa_cuentas(id),
  CONSTRAINT fk_mcl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS comandas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  cuenta_id BIGINT UNSIGNED NULL,
  venta_id BIGINT UNSIGNED NULL,
  area_produccion_id BIGINT UNSIGNED NOT NULL,
  estado ENUM('PENDIENTE','ENVIADA','PREPARANDO','LISTA','ENTREGADA','CANCELADA') NOT NULL DEFAULT 'PENDIENTE',
  enviada_at DATETIME NULL,
  lista_at DATETIME NULL,
  entregada_at DATETIME NULL,
  creada_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_comandas_estado (negocio_id, sucursal_id, estado, creada_at),
  KEY idx_comandas_area (negocio_id, sucursal_id, area_produccion_id, estado),
  CONSTRAINT fk_comandas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_comandas_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_comandas_cuenta FOREIGN KEY (cuenta_id) REFERENCES mesa_cuentas(id),
  CONSTRAINT fk_comandas_venta FOREIGN KEY (venta_id) REFERENCES ventas(id),
  CONSTRAINT fk_comandas_area FOREIGN KEY (area_produccion_id) REFERENCES areas_produccion(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS comanda_lineas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  comanda_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,3) NOT NULL,
  notas VARCHAR(255) NULL,
  modificadores_json LONGTEXT NULL,
  estado ENUM('PENDIENTE','PREPARANDO','LISTA','ENTREGADA','CANCELADA') NOT NULL DEFAULT 'PENDIENTE',
  PRIMARY KEY (id),
  KEY idx_cl_comanda (comanda_id),
  KEY idx_cl_producto (producto_id),
  CONSTRAINT fk_cl_comanda FOREIGN KEY (comanda_id) REFERENCES comandas(id),
  CONSTRAINT fk_cl_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS materias_primas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  unidad_base VARCHAR(15) NOT NULL,
  costo_promedio DECIMAL(18,5) NOT NULL DEFAULT 0,
  estado ENUM('activo','inactivo') NOT NULL DEFAULT 'activo',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_materias_negocio (negocio_id, estado, nombre),
  CONSTRAINT fk_mp_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS recetas (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  producto_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(180) NOT NULL,
  rendimiento DECIMAL(18,5) NOT NULL DEFAULT 1,
  estado ENUM('activa','inactiva') NOT NULL DEFAULT 'activa',
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_receta_producto (negocio_id, producto_id),
  CONSTRAINT fk_recetas_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_recetas_producto FOREIGN KEY (producto_id) REFERENCES productos(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS receta_detalles (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  receta_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  unidad_base VARCHAR(15) NOT NULL,
  merma_porcentaje DECIMAL(8,5) NOT NULL DEFAULT 0,
  afecta_inventario TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (id),
  KEY idx_rd_receta (receta_id),
  KEY idx_rd_materia (materia_prima_id),
  CONSTRAINT fk_rd_receta FOREIGN KEY (receta_id) REFERENCES recetas(id),
  CONSTRAINT fk_rd_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS inventario (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  stock_actual DECIMAL(18,5) NOT NULL DEFAULT 0,
  stock_minimo DECIMAL(18,5) NOT NULL DEFAULT 0,
  costo_promedio DECIMAL(18,5) NOT NULL DEFAULT 0,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_inventario_insumo_sucursal (negocio_id, sucursal_id, materia_prima_id),
  KEY idx_inventario_stock (negocio_id, sucursal_id, stock_actual),
  CONSTRAINT fk_inv_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_inv_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_inv_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS kardex (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NOT NULL,
  sucursal_id BIGINT UNSIGNED NOT NULL,
  materia_prima_id BIGINT UNSIGNED NOT NULL,
  tipo_movimiento ENUM('COMPRA','VENTA','COMANDA_CONSUMO_PENDIENTE','VENTA_CONFIRMADA','AJUSTE_POSITIVO','AJUSTE_NEGATIVO','MERMA','TRASLADO_SALIDA','TRASLADO_ENTRADA','PRODUCCION','REVERSA') NOT NULL,
  cantidad DECIMAL(18,5) NOT NULL,
  costo DECIMAL(18,5) NOT NULL DEFAULT 0,
  referencia_tipo VARCHAR(60) NULL,
  referencia_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  motivo VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_kardex_item_fecha (negocio_id, sucursal_id, materia_prima_id, creado_at),
  KEY idx_kardex_referencia (referencia_tipo, referencia_id),
  CONSTRAINT fk_kardex_negocio FOREIGN KEY (negocio_id) REFERENCES negocios(id),
  CONSTRAINT fk_kardex_sucursal FOREIGN KEY (sucursal_id) REFERENCES sucursales(id),
  CONSTRAINT fk_kardex_materia FOREIGN KEY (materia_prima_id) REFERENCES materias_primas(id),
  CONSTRAINT fk_kardex_usuario FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS auditoria (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NULL,
  sucursal_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  accion VARCHAR(120) NOT NULL,
  modulo VARCHAR(120) NULL,
  referencia_tipo VARCHAR(80) NULL,
  referencia_id BIGINT UNSIGNED NULL,
  detalle LONGTEXT NULL,
  ip VARCHAR(45) NULL,
  user_agent VARCHAR(255) NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_auditoria_negocio_fecha (negocio_id, creado_at),
  KEY idx_auditoria_referencia (referencia_tipo, referencia_id),
  KEY idx_auditoria_usuario (usuario_id, creado_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS seguridad_eventos (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  negocio_id BIGINT UNSIGNED NULL,
  usuario_id BIGINT UNSIGNED NULL,
  tipo VARCHAR(80) NOT NULL,
  severidad ENUM('baja','media','alta','critica') NOT NULL DEFAULT 'media',
  ip_hash CHAR(64) NULL,
  detalle LONGTEXT NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  KEY idx_seguridad_tipo_fecha (tipo, creado_at),
  KEY idx_seguridad_ip (ip_hash, creado_at),
  KEY idx_seguridad_negocio (negocio_id, creado_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rate_limits (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  ip_hash CHAR(64) NOT NULL,
  accion VARCHAR(80) NOT NULL,
  window_start DATETIME NOT NULL,
  attempts INT UNSIGNED NOT NULL DEFAULT 1,
  blocked_until DATETIME NULL,
  creado_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_at DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_rate_window (ip_hash, accion, window_start),
  KEY idx_rate_blocked (blocked_until)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
