-- Partner (distributor / dealer) stock balances
CREATE TABLE IF NOT EXISTS partner_stock (
  id INT AUTO_INCREMENT PRIMARY KEY,
  owner_type ENUM('distributor','dealer') NOT NULL,
  owner_id INT NOT NULL,
  product_id INT NOT NULL,
  quantity INT NOT NULL DEFAULT 0,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uq_partner_product (owner_type, owner_id, product_id),
  FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
  INDEX idx_partner_owner (owner_type, owner_id)
) ENGINE=InnoDB;

CREATE TABLE IF NOT EXISTS partner_stock_movements (
  id INT AUTO_INCREMENT PRIMARY KEY,
  owner_type ENUM('distributor','dealer') NOT NULL,
  owner_id INT NOT NULL,
  product_id INT NOT NULL,
  change_qty INT NOT NULL,
  balance_after INT NOT NULL DEFAULT 0,
  reason VARCHAR(50) NOT NULL,
  reference_type VARCHAR(50) DEFAULT NULL,
  reference_id INT DEFAULT NULL,
  notes TEXT,
  created_by INT DEFAULT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_psm_owner (owner_type, owner_id),
  INDEX idx_psm_product (product_id),
  FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
) ENGINE=InnoDB;
