-- +goose Up
CREATE TABLE profiles (
    user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
    preferred_name VARCHAR(100),
    profile_icon_url TEXT,
    headline VARCHAR(255),
    bio TEXT,
    timezone VARCHAR(100),
    locale VARCHAR(20),
    grade_level VARCHAR(100),
    learning_goal TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO profiles (user_id)
SELECT id
FROM users
ON CONFLICT (user_id) DO NOTHING;

-- +goose StatementBegin
CREATE OR REPLACE FUNCTION ensure_profile_for_user()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO profiles (user_id)
    VALUES (NEW.id)
    ON CONFLICT (user_id) DO NOTHING;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- +goose StatementEnd

CREATE TRIGGER profiles_updated_at BEFORE UPDATE ON profiles
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();

CREATE TRIGGER users_ensure_profile_after_insert AFTER INSERT ON users
    FOR EACH ROW EXECUTE FUNCTION ensure_profile_for_user();

-- +goose Down
DROP TRIGGER IF EXISTS users_ensure_profile_after_insert ON users;
DROP TRIGGER IF EXISTS profiles_updated_at ON profiles;
DROP FUNCTION IF EXISTS ensure_profile_for_user();
DROP TABLE IF EXISTS profiles;
