-- Migration: Independent Funding Rounds and Pot System

-- 1. Create funding_rounds table
CREATE TABLE IF NOT EXISTS funding_rounds (
    id INT AUTO_INCREMENT PRIMARY KEY,
    startup_id INT NOT NULL,
    funding_goal DECIMAL(15, 2) NOT NULL,
    funding_raised DECIMAL(15, 2) DEFAULT 0.00,
    status ENUM('Active', 'Closed', 'Cancelled') DEFAULT 'Active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (startup_id) REFERENCES startups(id) ON DELETE CASCADE
);

-- 2. Modify investments table to link to funding_rounds
ALTER TABLE investments ADD COLUMN funding_round_id INT AFTER startup_id;
ALTER TABLE investments ADD FOREIGN KEY (funding_round_id) REFERENCES funding_rounds(id) ON DELETE CASCADE;

-- 3. Update startups table to allow NULL founder_id (for deleted accounts)
ALTER TABLE startups DROP FOREIGN KEY startups_ibfk_1;
ALTER TABLE startups MODIFY founder_id INT NULL;
ALTER TABLE startups ADD CONSTRAINT startups_founder_fk FOREIGN KEY (founder_id) REFERENCES users(id) ON DELETE SET NULL;

-- 4. Seed initial funding rounds from existing startup data if any
INSERT INTO funding_rounds (startup_id, funding_goal, funding_raised, status, created_at)
SELECT id, funding_target, funding_raised, 'Active', created_at FROM startups;

-- 5. Link existing investments to the newly created rounds
UPDATE investments i
JOIN funding_rounds fr ON i.startup_id = fr.startup_id
SET i.funding_round_id = fr.id;
