-- CreateTable
CREATE TABLE "managed_registers" (
    "id" TEXT NOT NULL,
    "tenant_id" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "description" TEXT,
    "columns" JSONB NOT NULL DEFAULT '[]',
    "review_cycle" TEXT,
    "responsible" TEXT,
    "supplier_link" BOOLEAN NOT NULL DEFAULT false,
    "asset_link" BOOLEAN NOT NULL DEFAULT false,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "managed_registers_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "register_rows" (
    "id" TEXT NOT NULL,
    "tenant_id" TEXT NOT NULL,
    "register_id" TEXT NOT NULL,
    "values" JSONB NOT NULL DEFAULT '{}',
    "supplier_ref" TEXT,
    "asset_ref" TEXT,
    "order_idx" INTEGER NOT NULL DEFAULT 0,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "register_rows_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "managed_registers_tenant_id_idx" ON "managed_registers"("tenant_id");

-- CreateIndex
CREATE UNIQUE INDEX "managed_registers_tenant_id_code_key" ON "managed_registers"("tenant_id", "code");

-- CreateIndex
CREATE INDEX "register_rows_tenant_id_register_id_idx" ON "register_rows"("tenant_id", "register_id");

-- AddForeignKey
ALTER TABLE "register_rows" ADD CONSTRAINT "register_rows_register_id_fkey" FOREIGN KEY ("register_id") REFERENCES "managed_registers"("id") ON DELETE CASCADE ON UPDATE CASCADE;


-- RLS für die neuen mandantenbezogenen Tabellen.
DO $$
DECLARE t text;
BEGIN
  FOREACH t IN ARRAY ARRAY['managed_registers','register_rows'] LOOP
    EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', t);
    EXECUTE format('CREATE POLICY tenant_isolation ON %I USING (tenant_id = current_setting(''app.tenant_id'', true))', t);
  END LOOP;
END $$;
