-- Extension 4: Meal Planning
-- Recipes, weekly meal plans, and shopping lists (single-user, no RLS)

CREATE TABLE IF NOT EXISTS recipes (
    id               UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name             TEXT NOT NULL,
    cuisine          TEXT,
    prep_time_minutes INTEGER,
    cook_time_minutes INTEGER,
    servings         INTEGER,
    ingredients      JSONB NOT NULL DEFAULT '[]',
    instructions     JSONB NOT NULL DEFAULT '[]',
    tags             TEXT[] NOT NULL DEFAULT '{}',
    rating           INTEGER CHECK (rating >= 1 AND rating <= 5),
    notes            TEXT,
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS meal_plans (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    week_start DATE NOT NULL,
    day_of_week TEXT NOT NULL,
    meal_type  TEXT NOT NULL CHECK (meal_type IN ('breakfast', 'lunch', 'dinner', 'snack')),
    recipe_id  UUID REFERENCES recipes(id) ON DELETE SET NULL,
    custom_meal TEXT,
    servings   INTEGER,
    notes      TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS shopping_lists (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    week_start DATE NOT NULL UNIQUE,
    items      JSONB NOT NULL DEFAULT '[]',
    notes      TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_recipes_cuisine    ON recipes(cuisine);
CREATE INDEX IF NOT EXISTS idx_recipes_tags       ON recipes USING GIN (tags);
CREATE INDEX IF NOT EXISTS idx_meal_plans_week    ON meal_plans(week_start);
CREATE INDEX IF NOT EXISTS idx_shopping_lists_week ON shopping_lists(week_start);

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

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