-- Author: Hayden Hargreaves (hhargreaves2006@gmail.com)
-- Desc:   Create tables for the recipe tags and mapping tags to recipes.
-- Date:   07/12/2025

BEGIN;

-- Create the tags table itself
CREATE TABLE IF NOT EXISTS Tags (
  Id SERIAL PRIMARY KEY NOT NULL, 
  Name VARCHAR(32) UNIQUE NOT NULL,
  Created TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Create the recipe tag table to map tags to a recipe. This DB will be dynamically 
-- cleared when recipes or tags are deleted. This will prevent issues when deleting 
-- tags or recipes.
CREATE TABLE IF NOT EXISTS RecipeTags (
  Id SERIAL PRIMARY KEY NOT NULL, 
  RecipeId INT NOT NULL,
  TagId INT NOT NULL,
  Created TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  CONSTRAINT fk_recipe_id FOREIGN KEY (RecipeId) REFERENCES Recipes (Id) ON DELETE CASCADE,
  CONSTRAINT fk_tag_id FOREIGN KEY (TagId) REFERENCES Tags (Id) ON DELETE CASCADE
);

COMMIT;
