-- Extension 2: Home Maintenance Tracker
-- Tracks recurring maintenance tasks and logs completed work (single-user, no RLS)

CREATE TABLE IF NOT EXISTS maintenance_tasks (
    id             UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name           TEXT NOT NULL,
    category       TEXT,
    frequency_days INTEGER,
    last_completed TIMESTAMPTZ,
    next_due       TIMESTAMPTZ,
    priority       TEXT NOT NULL DEFAULT 'medium' CHECK (priority IN ('low', 'medium', 'high', 'urgent')),
    notes          TEXT,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS maintenance_logs (
    id           UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    task_id      UUID NOT NULL REFERENCES maintenance_tasks(id) ON DELETE CASCADE,
    completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    performed_by TEXT,
    cost         DECIMAL(10, 2),
    notes        TEXT,
    next_action  TEXT
);

CREATE INDEX IF NOT EXISTS idx_maintenance_tasks_next_due ON maintenance_tasks(next_due);
CREATE INDEX IF NOT EXISTS idx_maintenance_logs_task ON maintenance_logs(task_id, completed_at DESC);

DROP TRIGGER IF EXISTS update_maintenance_tasks_updated_at ON maintenance_tasks;
CREATE TRIGGER update_maintenance_tasks_updated_at
    BEFORE UPDATE ON maintenance_tasks
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE OR REPLACE FUNCTION update_task_after_maintenance_log()
RETURNS TRIGGER AS $$
DECLARE
    task_frequency INTEGER;
BEGIN
    SELECT frequency_days INTO task_frequency FROM maintenance_tasks WHERE id = NEW.task_id;
    UPDATE maintenance_tasks
    SET last_completed = NEW.completed_at,
        next_due = CASE
            WHEN task_frequency IS NOT NULL THEN NEW.completed_at + (task_frequency || ' days')::INTERVAL
            ELSE NULL
        END,
        updated_at = now()
    WHERE id = NEW.task_id;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS update_task_after_log ON maintenance_logs;
CREATE TRIGGER update_task_after_log
    AFTER INSERT ON maintenance_logs
    FOR EACH ROW EXECUTE FUNCTION update_task_after_maintenance_log();
