-- Salla Migrator DB Schema

CREATE TABLE IF NOT EXISTS products (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  source VARCHAR(50) NOT NULL DEFAULT 'salla',
  source_url VARCHAR(1024) NOT NULL,
  source_product_id VARCHAR(64) NULL,
  sku VARCHAR(128) NULL,
  name VARCHAR(512) NOT NULL,
  description_html MEDIUMTEXT NULL,
  description_text MEDIUMTEXT NULL,
  price DECIMAL(12,2) NULL,
  currency VARCHAR(8) NOT NULL DEFAULT 'SAR',
  brand VARCHAR(255) NULL,
  availability VARCHAR(255) NULL,
  categories_json JSON NULL,
  main_image_url VARCHAR(1024) NULL,
  status VARCHAR(30) NOT NULL DEFAULT 'new',
  last_scraped_at DATETIME NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_products_source_url (source_url),
  UNIQUE KEY uq_products_sku (sku),
  KEY idx_products_source_product_id (source_product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS product_images (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  product_id BIGINT UNSIGNED NOT NULL,
  image_url VARCHAR(1024) NOT NULL,
  local_path VARCHAR(1024) NULL,
  sort_order INT NOT NULL DEFAULT 0,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_product_images (product_id, image_url),
  CONSTRAINT fk_product_images_product FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS scrape_jobs (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  job_type VARCHAR(20) NOT NULL, -- product | category | file
  target VARCHAR(2048) NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending | running | done | failed
  message MEDIUMTEXT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY idx_jobs_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS logs (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  level VARCHAR(10) NOT NULL,
  context VARCHAR(50) NOT NULL,
  message MEDIUMTEXT NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
