-- src/main/resources/db/migration/V2__households.sql

-- Households & Members (H2/PG compatible)
CREATE TABLE households (
                            id UUID PRIMARY KEY,
                            name VARCHAR(120) NOT NULL,
                            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE household_members (
                                   id UUID PRIMARY KEY,
                                   household_id UUID NOT NULL REFERENCES households(id) ON DELETE CASCADE,
                                   user_sub VARCHAR(64) NOT NULL,
                                   email VARCHAR(255),
                                   display_name VARCHAR(120),
                                   role VARCHAR(16) NOT NULL,
                                   created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                                   UNIQUE (household_id, user_sub)
);

-- Optional: enforce role values (H2 accepts the CHECK too)
ALTER TABLE household_members
    ADD CONSTRAINT chk_household_role CHECK (role IN ('OWNER','MEMBER'));

CREATE INDEX idx_household_members_user_sub ON household_members(user_sub);
CREATE INDEX idx_household_members_household ON household_members(household_id);
