-- Migration for Enhanced Employee Management

-- 1. Alter employees table to add required fields
ALTER TABLE employees ADD COLUMN first_name VARCHAR(100) AFTER tenant_id;
ALTER TABLE employees ADD COLUMN last_name VARCHAR(100) AFTER first_name;
ALTER TABLE employees ADD COLUMN start_date DATE AFTER position;
ALTER TABLE employees ADD COLUMN is_limited BOOLEAN DEFAULT TRUE AFTER start_date;
ALTER TABLE employees ADD COLUMN user_id INT NULL AFTER is_limited;
ALTER TABLE employees ADD CONSTRAINT fk_employee_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;

-- Migrate existing names to first/last (rough split)
UPDATE employees SET first_name = SUBSTRING_INDEX(name, ' ', 1), last_name = SUBSTRING_INDEX(name, ' ', -1) WHERE name LIKE '% %';
UPDATE employees SET first_name = name, last_name = '' WHERE name NOT LIKE '% %';

-- 2. Wage History Table
CREATE TABLE IF NOT EXISTS employee_wages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL,
    employee_id INT NOT NULL,
    hourly_rate DECIMAL(10, 2) NOT NULL,
    effective_date DATE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE CASCADE
);

-- 3. Teams Table
CREATE TABLE IF NOT EXISTS teams (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tenant_id INT NOT NULL,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
);

-- 4. Employee-Team Link (Many-to-Many)
CREATE TABLE IF NOT EXISTS employee_teams (
    employee_id INT NOT NULL,
    team_id INT NOT NULL,
    tenant_id INT NOT NULL,
    PRIMARY KEY (employee_id, team_id),
    FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE CASCADE,
    FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,
    FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
);

-- Seed some teams
INSERT IGNORE INTO teams (tenant_id, name) VALUES (1, 'Engineering');
INSERT IGNORE INTO teams (tenant_id, name) VALUES (1, 'R&D');
INSERT IGNORE INTO teams (tenant_id, name) VALUES (1, 'Product Management');
