-- Initial Schema for SR&ED Manager
CREATE TABLE IF NOT EXISTS tenants (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    role ENUM('global_admin', 'tenant_admin', 'staff') DEFAULT 'staff',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE SET NULL
);

CREATE TABLE IF NOT EXISTS projects (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL,
    name VARCHAR(255) NOT NULL,
    code VARCHAR(50) NOT NULL,
    status ENUM('active', 'completed', 'on_hold') DEFAULT 'active',
    start_date DATE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS activity_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL,
    user_id INT,
    action VARCHAR(255) NOT NULL,
    details TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
);

-- Seed Initial Demo Data
INSERT IGNORE INTO tenants (id, name) VALUES (1, 'Acme Research Corp');
INSERT IGNORE INTO users (id, tenant_id, name, email, role) VALUES (1, 1, 'John Manager', 'john@acme.com', 'tenant_admin');
INSERT IGNORE INTO projects (tenant_id, name, code, start_date) VALUES (1, 'Project Alpha: Quantum AI', 'PA-001', '2025-01-01');
INSERT IGNORE INTO activity_log (tenant_id, user_id, action, details) VALUES (1, 1, 'System Setup', 'Initial tenant environment created.');
