-- Fase 11: sedes / sucursales por negocio
SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS locations (
  id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id  BIGINT UNSIGNED NOT NULL,
  name         VARCHAR(120) NOT NULL,
  address      VARCHAR(255) NULL,
  phone        VARCHAR(30) NULL,
  timezone     VARCHAR(64) NULL,
  is_default   TINYINT(1) NOT NULL DEFAULT 0,
  is_active    TINYINT(1) NOT NULL DEFAULT 1,
  sort_order   INT NOT NULL DEFAULT 0,
  created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY (business_id),
  CONSTRAINT fk_loc_biz FOREIGN KEY (business_id) REFERENCES businesses(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Sede por defecto para cada negocio existente
INSERT INTO locations (business_id, name, address, phone, timezone, is_default, is_active)
SELECT b.id, 'Sede principal', b.address, b.phone, b.timezone, 1, 1
FROM businesses b
WHERE NOT EXISTS (SELECT 1 FROM locations l WHERE l.business_id = b.id);

-- Asignación de sede a staff / citas / cajas
ALTER TABLE staff
  ADD COLUMN location_id BIGINT UNSIGNED NULL AFTER business_id,
  ADD KEY (location_id),
  ADD CONSTRAINT fk_staff_loc FOREIGN KEY (location_id) REFERENCES locations(id) ON DELETE SET NULL;

ALTER TABLE appointments
  ADD COLUMN location_id BIGINT UNSIGNED NULL AFTER business_id,
  ADD KEY (location_id),
  ADD CONSTRAINT fk_app_loc FOREIGN KEY (location_id) REFERENCES locations(id) ON DELETE SET NULL;

ALTER TABLE cash_sessions
  ADD COLUMN location_id BIGINT UNSIGNED NULL AFTER business_id,
  ADD KEY (location_id),
  ADD CONSTRAINT fk_cash_loc FOREIGN KEY (location_id) REFERENCES locations(id) ON DELETE SET NULL;

-- Bootstrap: asignar todo lo existente a la sede principal de su negocio
UPDATE staff s
  JOIN locations l ON l.business_id = s.business_id AND l.is_default = 1
  SET s.location_id = l.id
  WHERE s.location_id IS NULL;

UPDATE appointments a
  JOIN locations l ON l.business_id = a.business_id AND l.is_default = 1
  SET a.location_id = l.id
  WHERE a.location_id IS NULL;

UPDATE cash_sessions c
  JOIN locations l ON l.business_id = c.business_id AND l.is_default = 1
  SET c.location_id = l.id
  WHERE c.location_id IS NULL;
