-- AlterTable: add shortName, archivedAt to Organization
ALTER TABLE "Organization" ADD COLUMN "shortName" TEXT;
ALTER TABLE "Organization" ADD COLUMN "archivedAt" TIMESTAMP(3);

-- CreateTable: BankAccount
CREATE TABLE "BankAccount" (
    "id" UUID NOT NULL,
    "organizationId" UUID NOT NULL,
    "name" TEXT NOT NULL,
    "bankName" TEXT,
    "bankBik" TEXT,
    "accountNumber" TEXT,
    "corrAccount" TEXT,
    "currency" TEXT NOT NULL DEFAULT 'RUB',
    "isPrimary" BOOLEAN NOT NULL DEFAULT false,
    "archivedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

CREATE INDEX "BankAccount_organizationId_idx" ON "BankAccount"("organizationId");

ALTER TABLE "BankAccount" ADD CONSTRAINT "BankAccount_organizationId_fkey"
    FOREIGN KEY ("organizationId") REFERENCES "Organization"("id")
    ON DELETE CASCADE ON UPDATE CASCADE;

-- AlterTable: add bankAccountId on TochkaCredential
ALTER TABLE "TochkaCredential" ADD COLUMN "bankAccountId" UUID;
ALTER TABLE "TochkaCredential" ADD CONSTRAINT "TochkaCredential_bankAccountId_fkey"
    FOREIGN KEY ("bankAccountId") REFERENCES "BankAccount"("id")
    ON DELETE SET NULL ON UPDATE CASCADE;

-- Data migration: для каждой организации с заполненным bank* — создать запись BankAccount(isPrimary=true)
INSERT INTO "BankAccount" ("id", "organizationId", "name", "bankName", "bankBik", "accountNumber", "currency", "isPrimary", "createdAt", "updatedAt")
SELECT
    gen_random_uuid(),
    o."id",
    'Основной счёт',
    o."bankName",
    o."bankBik",
    o."bankAccount",
    'RUB',
    true,
    NOW(),
    NOW()
FROM "Organization" o
WHERE o."bankName" IS NOT NULL OR o."bankBik" IS NOT NULL OR o."bankAccount" IS NOT NULL;
