-- Stock Management System (SMS) Database
-- StockHub Ltd - Kigali City, Rwanda

CREATE DATABASE IF NOT EXISTS SMS;
USE SMS;

CREATE TABLE IF NOT EXISTS User (
    userId INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS Product (
    productCode VARCHAR(20) PRIMARY KEY,
    productName VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,
    quantityInStock INT NOT NULL DEFAULT 0,
    unitPrice DECIMAL(10, 2) NOT NULL,
    supplierName VARCHAR(100) NOT NULL,
    dateReceived DATE NOT NULL
);

CREATE TABLE IF NOT EXISTS Warehouse (
    warehouseCode VARCHAR(20) PRIMARY KEY,
    warehouseName VARCHAR(100) NOT NULL,
    warehouseLocation VARCHAR(150) NOT NULL
);

CREATE TABLE IF NOT EXISTS StockTransaction (
    transactionId INT AUTO_INCREMENT PRIMARY KEY,
    productCode VARCHAR(20) NOT NULL,
    warehouseCode VARCHAR(20) NOT NULL,
    transactionDate DATE NOT NULL,
    quantityMoved INT NOT NULL,
    transactionType ENUM('IN', 'OUT') NOT NULL,
    FOREIGN KEY (productCode) REFERENCES Product(productCode) ON DELETE RESTRICT ON UPDATE CASCADE,
    FOREIGN KEY (warehouseCode) REFERENCES Warehouse(warehouseCode) ON DELETE RESTRICT ON UPDATE CASCADE
);

INSERT INTO Product (productCode, productName, category, quantityInStock, unitPrice, supplierName, dateReceived) VALUES
('P001', 'Rice 25kg', 'Food', 100, 35000.00, 'Kigali Foods Ltd', '2026-01-15'),
('P002', 'Cooking Oil 5L', 'Food', 50, 12000.00, 'Rwanda Oil Co', '2026-02-01')
ON DUPLICATE KEY UPDATE productName = VALUES(productName);

INSERT INTO Warehouse (warehouseCode, warehouseName, warehouseLocation) VALUES
('W001', 'Main Warehouse', 'Kigali City, Nyarugenge'),
('W002', 'Branch Warehouse', 'Kigali City, Gasabo')
ON DUPLICATE KEY UPDATE warehouseName = VALUES(warehouseName);
