-- CreateExtension
CREATE EXTENSION IF NOT EXISTS "postgis";

-- CreateTable
CREATE TABLE "grid_regions" (
    "id" UUID NOT NULL,
    "name" TEXT NOT NULL,
    "code" TEXT NOT NULL,
    "iso" TEXT NOT NULL,
    "boundary" geography(MultiPolygon, 4326) NOT NULL,
    "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "datacenters" (
    "id" UUID NOT NULL,
    "name" TEXT NOT NULL,
    "operator" TEXT NOT NULL,
    "location" geography(Point, 4326) NOT NULL,
    "capacity_mw" DOUBLE PRECISION NOT NULL,
    "status" TEXT NOT NULL,
    "year_opened" INTEGER NOT NULL,
    "region_id" UUID NOT NULL,
    "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "electricity_prices" (
    "id" UUID NOT NULL,
    "region_id" UUID NOT NULL,
    "price_mwh" DOUBLE PRECISION NOT NULL,
    "demand_mw" DOUBLE PRECISION NOT NULL,
    "timestamp" TIMESTAMPTZ NOT NULL,
    "source" TEXT NOT NULL,

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

-- CreateTable
CREATE TABLE "commodity_prices" (
    "id" UUID NOT NULL,
    "commodity" TEXT NOT NULL,
    "price" DOUBLE PRECISION NOT NULL,
    "unit" TEXT NOT NULL,
    "timestamp" TIMESTAMPTZ NOT NULL,
    "source" TEXT NOT NULL,

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

-- CreateTable
CREATE TABLE "generation_mix" (
    "id" UUID NOT NULL,
    "region_id" UUID NOT NULL,
    "fuel_type" TEXT NOT NULL,
    "generation_mw" DOUBLE PRECISION NOT NULL,
    "timestamp" TIMESTAMPTZ NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX "grid_regions_code_key" ON "grid_regions"("code");

-- CreateIndex
CREATE INDEX "electricity_prices_region_id_timestamp_idx" ON "electricity_prices"("region_id", "timestamp");

-- CreateIndex
CREATE INDEX "commodity_prices_commodity_timestamp_idx" ON "commodity_prices"("commodity", "timestamp");

-- CreateIndex
CREATE INDEX "generation_mix_region_id_timestamp_idx" ON "generation_mix"("region_id", "timestamp");

-- AddForeignKey
ALTER TABLE "datacenters" ADD CONSTRAINT "datacenters_region_id_fkey" FOREIGN KEY ("region_id") REFERENCES "grid_regions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "electricity_prices" ADD CONSTRAINT "electricity_prices_region_id_fkey" FOREIGN KEY ("region_id") REFERENCES "grid_regions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "generation_mix" ADD CONSTRAINT "generation_mix_region_id_fkey" FOREIGN KEY ("region_id") REFERENCES "grid_regions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
