-- Grow entries (one per plant batch lifecycle)
CREATE TABLE IF NOT EXISTS grow_entries (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    strain_id UUID REFERENCES strains(id),
    status VARCHAR(30) NOT NULL DEFAULT 'SEEDLING',
    started_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    expected_harvest_at TIMESTAMP WITH TIME ZONE,
    actual_harvest_at TIMESTAMP WITH TIME ZONE,
    harvested_grams NUMERIC(8,1),
    linked_batch_id UUID REFERENCES batches(id),
    notes TEXT,
    tenant_id UUID NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Grow stage transitions
CREATE TABLE IF NOT EXISTS grow_stage_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    grow_entry_id UUID NOT NULL REFERENCES grow_entries(id) ON DELETE CASCADE,
    stage VARCHAR(30) NOT NULL,
    started_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    ended_at TIMESTAMP WITH TIME ZONE,
    notes TEXT
);

-- Sensor readings
CREATE TABLE IF NOT EXISTS sensor_readings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    grow_entry_id UUID NOT NULL REFERENCES grow_entries(id) ON DELETE CASCADE,
    reading_type VARCHAR(30) NOT NULL,
    value NUMERIC(8,2) NOT NULL,
    unit VARCHAR(10) NOT NULL,
    recorded_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

-- Photos
CREATE TABLE IF NOT EXISTS grow_photos (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    grow_entry_id UUID NOT NULL REFERENCES grow_entries(id) ON DELETE CASCADE,
    file_path VARCHAR(500) NOT NULL,
    caption VARCHAR(255),
    taken_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);

-- Feeding schedule entries
CREATE TABLE IF NOT EXISTS feeding_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    grow_entry_id UUID NOT NULL REFERENCES grow_entries(id) ON DELETE CASCADE,
    nutrient_name VARCHAR(100) NOT NULL,
    amount_ml NUMERIC(8,1) NOT NULL,
    water_liters NUMERIC(8,1),
    ph_after NUMERIC(4,2),
    ec_after NUMERIC(6,2),
    fed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    notes TEXT
);

CREATE INDEX idx_grow_entries_tenant ON grow_entries(tenant_id);
CREATE INDEX idx_grow_entries_status ON grow_entries(status);
CREATE INDEX idx_sensor_readings_entry ON sensor_readings(grow_entry_id, recorded_at DESC);
CREATE INDEX idx_feeding_logs_entry ON feeding_logs(grow_entry_id, fed_at DESC);
CREATE INDEX idx_grow_photos_entry ON grow_photos(grow_entry_id);
CREATE INDEX idx_grow_stage_logs_entry ON grow_stage_logs(grow_entry_id);
