-- CreateTable
CREATE TABLE "contract_templates" (
    "template_id" SERIAL NOT NULL,
    "version" VARCHAR(20) NOT NULL,
    "title" VARCHAR(200) NOT NULL,
    "content" TEXT NOT NULL,
    "effective_from" TIMESTAMP(3) NOT NULL,
    "effective_to" TIMESTAMP(3),
    "is_active" BOOLEAN NOT NULL DEFAULT true,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "contract_templates_pkey" PRIMARY KEY ("template_id")
);

-- CreateTable
CREATE TABLE "contract_signing_tasks" (
    "task_id" BIGSERIAL NOT NULL,
    "order_no" VARCHAR(50) NOT NULL,
    "user_id" BIGINT NOT NULL,
    "account_sequence" VARCHAR(20) NOT NULL,
    "template_id" INTEGER NOT NULL,
    "contract_version" VARCHAR(20) NOT NULL,
    "contract_content" TEXT NOT NULL,
    "user_phone_number" VARCHAR(20),
    "user_real_name" VARCHAR(50),
    "user_id_card_number" VARCHAR(50),
    "tree_count" INTEGER NOT NULL,
    "total_amount" DECIMAL(20,8) NOT NULL,
    "province_code" VARCHAR(10) NOT NULL,
    "province_name" VARCHAR(50) NOT NULL,
    "city_code" VARCHAR(10) NOT NULL,
    "city_name" VARCHAR(50) NOT NULL,
    "status" VARCHAR(30) NOT NULL DEFAULT 'PENDING',
    "expires_at" TIMESTAMP(3) NOT NULL,
    "scrolled_to_bottom_at" TIMESTAMP(3),
    "acknowledged_at" TIMESTAMP(3),
    "signed_at" TIMESTAMP(3),
    "signature_cloud_url" VARCHAR(500),
    "signature_hash" VARCHAR(64),
    "signing_ip_address" VARCHAR(50),
    "signing_device_info" TEXT,
    "signing_user_agent" VARCHAR(500),
    "signing_latitude" DECIMAL(10,8),
    "signing_longitude" DECIMAL(11,8),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "contract_signing_tasks_pkey" PRIMARY KEY ("task_id")
);

-- CreateIndex
CREATE UNIQUE INDEX "contract_templates_version_key" ON "contract_templates"("version");

-- CreateIndex
CREATE INDEX "contract_templates_is_active_effective_from_idx" ON "contract_templates"("is_active", "effective_from");

-- CreateIndex
CREATE UNIQUE INDEX "contract_signing_tasks_order_no_key" ON "contract_signing_tasks"("order_no");

-- CreateIndex
CREATE INDEX "contract_signing_tasks_user_id_idx" ON "contract_signing_tasks"("user_id");

-- CreateIndex
CREATE INDEX "contract_signing_tasks_status_idx" ON "contract_signing_tasks"("status");

-- CreateIndex
CREATE INDEX "contract_signing_tasks_expires_at_idx" ON "contract_signing_tasks"("expires_at");

-- CreateIndex
CREATE INDEX "contract_signing_tasks_status_expires_at_idx" ON "contract_signing_tasks"("status", "expires_at");

-- AddForeignKey
ALTER TABLE "contract_signing_tasks" ADD CONSTRAINT "contract_signing_tasks_template_id_fkey" FOREIGN KEY ("template_id") REFERENCES "contract_templates"("template_id") ON DELETE RESTRICT ON UPDATE CASCADE;
