CREATE TABLE IF NOT EXISTS warehouses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

CREATE TABLE IF NOT EXISTS stock (
    id INT AUTO_INCREMENT PRIMARY KEY,
    article_id INT NOT NULL,
    warehouse_id INT NOT NULL,
    quantity DECIMAL(10,2) DEFAULT 0.00,
    UNIQUE KEY unique_article_warehouse (article_id, warehouse_id),
    FOREIGN KEY (article_id) REFERENCES articles(id),
    FOREIGN KEY (warehouse_id) REFERENCES warehouses(id)
);

CREATE TABLE IF NOT EXISTS stock_movements (
    id INT AUTO_INCREMENT PRIMARY KEY,
    article_id INT NOT NULL,
    warehouse_id INT NOT NULL,
    type ENUM('in', 'out', 'correction') NOT NULL,
    quantity DECIMAL(10,2) NOT NULL,
    reference VARCHAR(100),
    created_by INT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (article_id) REFERENCES articles(id),
    FOREIGN KEY (warehouse_id) REFERENCES warehouses(id),
    FOREIGN KEY (created_by) REFERENCES users(id)
);

INSERT INTO warehouses (name)
SELECT 'Hauptlager'
WHERE NOT EXISTS (SELECT 1 FROM warehouses WHERE name = 'Hauptlager');
