CREATE TYPE "ExpenseRecurrence" AS ENUM ('NONE', 'MONTHLY');

CREATE TABLE "accounting_periods" (
  "id" TEXT NOT NULL,
  "name" TEXT NOT NULL,
  "starts_at" TIMESTAMP(3) NOT NULL,
  "ends_at" TIMESTAMP(3) NOT NULL,
  "is_current" BOOLEAN NOT NULL DEFAULT false,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "accounting_periods_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "accounting_periods_name_key" ON "accounting_periods"("name");
CREATE UNIQUE INDEX "accounting_periods_is_current_key" ON "accounting_periods"("is_current") WHERE "is_current" = true;

INSERT INTO "accounting_periods" (
  "id",
  "name",
  "starts_at",
  "ends_at",
  "is_current",
  "created_at",
  "updated_at"
)
VALUES (
  'period_current',
  CONCAT('Haushalt ', EXTRACT(YEAR FROM CURRENT_DATE)::text),
  date_trunc('year', CURRENT_DATE)::timestamp(3),
  (date_trunc('year', CURRENT_DATE) + interval '1 year' - interval '1 day')::timestamp(3),
  true,
  CURRENT_TIMESTAMP,
  CURRENT_TIMESTAMP
);

ALTER TABLE "budgets" ADD COLUMN "period_id" TEXT;
ALTER TABLE "expenses" ADD COLUMN "period_id" TEXT;
ALTER TABLE "expenses" ADD COLUMN "recurrence" "ExpenseRecurrence" NOT NULL DEFAULT 'NONE';

UPDATE "budgets"
SET "period_id" = 'period_current';

UPDATE "expenses"
SET "period_id" = 'period_current';

ALTER TABLE "budgets" ALTER COLUMN "period_id" SET NOT NULL;
ALTER TABLE "expenses" ALTER COLUMN "period_id" SET NOT NULL;

DROP INDEX "budgets_working_group_id_name_key";
CREATE UNIQUE INDEX "budgets_working_group_id_period_id_name_key" ON "budgets"("working_group_id", "period_id", "name");

ALTER TABLE "budgets"
  ADD CONSTRAINT "budgets_period_id_fkey"
  FOREIGN KEY ("period_id") REFERENCES "accounting_periods"("id")
  ON DELETE RESTRICT ON UPDATE CASCADE;

ALTER TABLE "expenses"
  ADD CONSTRAINT "expenses_period_id_fkey"
  FOREIGN KEY ("period_id") REFERENCES "accounting_periods"("id")
  ON DELETE RESTRICT ON UPDATE CASCADE;
