-- CreateEnum
CREATE TYPE "CalendarEventType" AS ENUM ('TASK', 'DEADLINE', 'COURT_DATE', 'HEARING', 'MEETING', 'FILING', 'FOLLOW_UP', 'REMINDER', 'OTHER');

-- CreateEnum
CREATE TYPE "CalendarEventStatus" AS ENUM ('ACTIVE', 'CANCELLED', 'COMPLETED');

-- CreateEnum
CREATE TYPE "ReminderChannel" AS ENUM ('IN_APP', 'EMAIL');

-- CreateEnum
CREATE TYPE "NotificationType" AS ENUM ('TASK_DUE', 'DEADLINE_APPROACHING', 'COURT_DATE_APPROACHING', 'EXPENSE_PENDING_APPROVAL', 'EXPENSE_APPROVED', 'EXPENSE_REJECTED', 'INVOICE_OVERDUE', 'DOCUMENT_REQUEST', 'CONFLICT_REVIEW_REQUIRED', 'GENERAL');

-- CreateEnum
CREATE TYPE "CommercialWorkspaceType" AS ENUM ('CONTRACT_DRAFTING_REVIEW', 'CONTRACT_DISPUTE', 'DEBT_RECOVERY', 'EMPLOYMENT', 'CORPORATE', 'PROPERTY_CONVEYANCING', 'COMMERCIAL_LITIGATION', 'ADR_ARBITRATION', 'REGULATORY_COMPLIANCE', 'DUE_DILIGENCE_ADVISORY');

-- CreateEnum
CREATE TYPE "VendorType" AS ENUM ('MEDICAL_PROVIDER', 'COURT_SERVICES', 'EXPERT', 'PROCESS_SERVER', 'AUCTIONEER', 'VALUER', 'TRANSLATOR', 'INVESTIGATOR', 'LAW_FIRM', 'GOVERNMENT_AGENCY', 'OTHER');

-- CreateEnum
CREATE TYPE "VendorBillStatus" AS ENUM ('DRAFT', 'SUBMITTED', 'APPROVED', 'REJECTED', 'PAID', 'CANCELLED');

-- CreateEnum
CREATE TYPE "ClientLedgerEntryType" AS ENUM ('RECEIPT', 'DISBURSEMENT', 'TRANSFER', 'FEE_DEDUCTION', 'REFUND', 'RETAINER_APPLIED');

-- CreateEnum
CREATE TYPE "ClientReceiptStatus" AS ENUM ('PENDING', 'CLEARED', 'BOUNCED', 'REFUNDED');

-- CreateEnum
CREATE TYPE "RetainerStatus" AS ENUM ('HELD', 'PARTIALLY_APPLIED', 'FULLY_APPLIED', 'REFUNDED');

-- CreateEnum
CREATE TYPE "JudgmentStatus" AS ENUM ('DELIVERED', 'UNDER_APPEAL', 'FINAL', 'SATISFIED', 'PARTIALLY_SATISFIED', 'UNSATISFIED');

-- CreateEnum
CREATE TYPE "ExecutionType" AS ENUM ('GARNISHEE_ORDER', 'ATTACHMENT', 'AUCTIONEER_APPOINTMENT', 'DEBTOR_SUMMONS', 'WARRANT_OF_ARREST', 'OTHER');

-- CreateEnum
CREATE TYPE "ExecutionActivityStatus" AS ENUM ('PENDING', 'IN_PROGRESS', 'COMPLETED', 'FAILED');

-- CreateEnum
CREATE TYPE "SettlementType" AS ENUM ('PRE_LITIGATION', 'DURING_LITIGATION', 'POST_JUDGMENT');

-- CreateEnum
CREATE TYPE "SettlementStatus" AS ENUM ('PROPOSED', 'AWAITING_CLIENT_AUTHORITY', 'PENDING_FIRST_APPROVAL', 'PENDING_SECOND_APPROVAL', 'APPROVED', 'REJECTED', 'COMPLETED', 'CANCELLED');

-- CreateEnum
CREATE TYPE "OfferDirection" AS ENUM ('INCOMING', 'OUTGOING');

-- CreateEnum
CREATE TYPE "OfferStatus" AS ENUM ('OPEN', 'ACCEPTED', 'REJECTED', 'EXPIRED', 'WITHDRAWN');

-- CreateEnum
CREATE TYPE "RemittanceStatus" AS ENUM ('DRAFT', 'PENDING_FIRST_APPROVAL', 'PENDING_SECOND_APPROVAL', 'APPROVED', 'DISBURSED', 'CANCELLED');

-- CreateEnum
CREATE TYPE "PortalRole" AS ENUM ('VIEWER', 'CONTRIBUTOR', 'ADMINISTRATOR');

-- CreateEnum
CREATE TYPE "MessageDirection" AS ENUM ('INBOUND', 'OUTBOUND');

-- CreateEnum
CREATE TYPE "CommunicationType" AS ENUM ('EMAIL', 'PHONE_CALL', 'MEETING', 'PORTAL_MESSAGE', 'NOTE', 'SMS', 'OTHER');

-- CreateEnum
CREATE TYPE "CommunicationDirection" AS ENUM ('INBOUND', 'OUTBOUND', 'INTERNAL');

-- CreateEnum
CREATE TYPE "CommunicationStatus" AS ENUM ('DRAFT', 'LOGGED', 'SENT', 'DELIVERED', 'FAILED');

-- CreateEnum
CREATE TYPE "OutboxStatus" AS ENUM ('PENDING', 'SENT', 'FAILED', 'CANCELLED');

-- CreateEnum
CREATE TYPE "JobStatus" AS ENUM ('PENDING', 'RUNNING', 'COMPLETED', 'FAILED', 'CANCELLED');

-- CreateTable
CREATE TABLE "calendar_events" (
    "id" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "description" TEXT,
    "eventType" "CalendarEventType" NOT NULL,
    "startAt" TIMESTAMP(3) NOT NULL,
    "endAt" TIMESTAMP(3),
    "allDay" BOOLEAN NOT NULL DEFAULT false,
    "caseId" TEXT,
    "matterId" TEXT,
    "taskId" TEXT,
    "deadlineId" TEXT,
    "createdBy" TEXT NOT NULL,
    "assignedTo" TEXT,
    "status" "CalendarEventStatus" NOT NULL DEFAULT 'ACTIVE',
    "externalRef" TEXT,
    "metadata" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "reminder_rules" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "targetType" TEXT NOT NULL,
    "offsetDays" INTEGER NOT NULL,
    "channel" "ReminderChannel" NOT NULL DEFAULT 'IN_APP',
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "notifications" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "body" TEXT NOT NULL,
    "type" "NotificationType" NOT NULL DEFAULT 'GENERAL',
    "entityType" TEXT,
    "entityId" TEXT,
    "caseId" TEXT,
    "isRead" BOOLEAN NOT NULL DEFAULT false,
    "readAt" TIMESTAMP(3),
    "deliveredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "document_versions" (
    "id" TEXT NOT NULL,
    "documentId" TEXT NOT NULL,
    "versionNumber" INTEGER NOT NULL,
    "storageKey" TEXT NOT NULL,
    "filePath" TEXT NOT NULL,
    "fileUrl" TEXT NOT NULL,
    "fileType" TEXT NOT NULL,
    "fileSize" INTEGER NOT NULL,
    "checksum" TEXT,
    "changeNotes" TEXT,
    "uploadedBy" TEXT NOT NULL,
    "isCurrent" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "commercial_workspaces" (
    "id" TEXT NOT NULL,
    "caseId" TEXT NOT NULL,
    "workspaceType" "CommercialWorkspaceType" NOT NULL,
    "parties" JSONB,
    "counterparties" JSONB,
    "relatedEntities" JSONB,
    "financialValues" JSONB,
    "riskNotes" TEXT,
    "specialistFields" JSONB,
    "checklistItems" JSONB,
    "documentGates" JSONB,
    "deadlineConfig" JSONB,
    "notes" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "vendors" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "type" "VendorType" NOT NULL DEFAULT 'OTHER',
    "email" TEXT,
    "phone" TEXT,
    "address" TEXT,
    "taxNumber" TEXT,
    "bankName" TEXT,
    "bankAccount" TEXT,
    "notes" TEXT,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "vendor_bills" (
    "id" TEXT NOT NULL,
    "vendorId" TEXT NOT NULL,
    "billNumber" TEXT NOT NULL,
    "caseId" TEXT,
    "description" TEXT NOT NULL,
    "amount" DECIMAL(14,2) NOT NULL,
    "taxAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "dueAt" TIMESTAMP(3),
    "status" "VendorBillStatus" NOT NULL DEFAULT 'DRAFT',
    "approvedBy" TEXT,
    "approvedAt" TIMESTAMP(3),
    "paidAt" TIMESTAMP(3),
    "paymentReference" TEXT,
    "journalId" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "client_bank_accounts" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "bankName" TEXT NOT NULL,
    "accountNumber" TEXT NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "client_ledger_entries" (
    "id" TEXT NOT NULL,
    "clientId" TEXT NOT NULL,
    "caseId" TEXT,
    "clientBankAccountId" TEXT NOT NULL,
    "entryType" "ClientLedgerEntryType" NOT NULL,
    "amount" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "description" TEXT NOT NULL,
    "reference" TEXT,
    "journalId" TEXT,
    "balanceAfter" DECIMAL(14,2) NOT NULL,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "client_receipts" (
    "id" TEXT NOT NULL,
    "clientId" TEXT NOT NULL,
    "caseId" TEXT,
    "clientBankAccountId" TEXT NOT NULL,
    "amount" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "receivedAt" TIMESTAMP(3) NOT NULL,
    "payerName" TEXT,
    "reference" TEXT,
    "description" TEXT NOT NULL,
    "status" "ClientReceiptStatus" NOT NULL DEFAULT 'PENDING',
    "clearedAt" TIMESTAMP(3),
    "journalId" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "retainers" (
    "id" TEXT NOT NULL,
    "clientId" TEXT NOT NULL,
    "caseId" TEXT,
    "amount" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "purpose" TEXT,
    "status" "RetainerStatus" NOT NULL DEFAULT 'HELD',
    "appliedAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "refundedAmount" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "receiptId" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "judgments" (
    "id" TEXT NOT NULL,
    "caseId" TEXT NOT NULL,
    "courtName" TEXT NOT NULL,
    "courtCaseNumber" TEXT NOT NULL,
    "deliveredAt" TIMESTAMP(3) NOT NULL,
    "principalAmount" DECIMAL(14,2),
    "interestBasis" TEXT,
    "interestRate" DECIMAL(6,4),
    "interestFrom" TIMESTAMP(3),
    "awardedCosts" DECIMAL(14,2),
    "taxedCosts" DECIMAL(14,2),
    "decreeName" TEXT,
    "complianceDueAt" TIMESTAMP(3),
    "notes" TEXT,
    "status" "JudgmentStatus" NOT NULL DEFAULT 'DELIVERED',
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "execution_activities" (
    "id" TEXT NOT NULL,
    "judgmentId" TEXT NOT NULL,
    "type" "ExecutionType" NOT NULL,
    "description" TEXT NOT NULL,
    "amount" DECIMAL(14,2),
    "reference" TEXT,
    "status" "ExecutionActivityStatus" NOT NULL DEFAULT 'PENDING',
    "executedAt" TIMESTAMP(3),
    "notes" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "settlements" (
    "id" TEXT NOT NULL,
    "caseId" TEXT NOT NULL,
    "judgmentId" TEXT,
    "type" "SettlementType" NOT NULL DEFAULT 'PRE_LITIGATION',
    "grossAmount" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "firmFees" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "vatOnFees" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "disbursements" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "clientNet" DECIMAL(14,2) NOT NULL,
    "status" "SettlementStatus" NOT NULL DEFAULT 'PROPOSED',
    "clientAuthorityAt" TIMESTAMP(3),
    "firstApprovalBy" TEXT,
    "firstApprovedAt" TIMESTAMP(3),
    "secondApprovalBy" TEXT,
    "secondApprovedAt" TIMESTAMP(3),
    "rejectionReason" TEXT,
    "notes" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "settlement_offers" (
    "id" TEXT NOT NULL,
    "settlementId" TEXT NOT NULL,
    "direction" "OfferDirection" NOT NULL,
    "amount" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "offeredAt" TIMESTAMP(3) NOT NULL,
    "expiresAt" TIMESTAMP(3),
    "advocateRecommendation" TEXT,
    "clientAuthority" BOOLEAN NOT NULL DEFAULT false,
    "status" "OfferStatus" NOT NULL DEFAULT 'OPEN',
    "notes" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "remittances" (
    "id" TEXT NOT NULL,
    "caseId" TEXT NOT NULL,
    "settlementId" TEXT NOT NULL,
    "grossAmount" DECIMAL(14,2) NOT NULL,
    "firmFees" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "vatOnFees" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "disbursements" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "obligations" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "holdbacks" DECIMAL(14,2) NOT NULL DEFAULT 0,
    "netToClient" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'KES',
    "status" "RemittanceStatus" NOT NULL DEFAULT 'DRAFT',
    "fundsReceivedAt" TIMESTAMP(3),
    "firstApprovalBy" TEXT,
    "firstApprovedAt" TIMESTAMP(3),
    "secondApprovalBy" TEXT,
    "secondApprovedAt" TIMESTAMP(3),
    "disbursedAt" TIMESTAMP(3),
    "disbursementReference" TEXT,
    "clientInstructions" TEXT,
    "statementNotes" TEXT,
    "createdBy" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "client_users" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "clientId" TEXT NOT NULL,
    "portalRole" "PortalRole" NOT NULL DEFAULT 'VIEWER',
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "invitedAt" TIMESTAMP(3),
    "activatedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "portal_authorizations" (
    "id" TEXT NOT NULL,
    "clientUserId" TEXT NOT NULL,
    "entityType" TEXT NOT NULL,
    "entityId" TEXT NOT NULL,
    "canView" BOOLEAN NOT NULL DEFAULT true,
    "canDownload" BOOLEAN NOT NULL DEFAULT false,
    "canComment" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "portal_messages" (
    "id" TEXT NOT NULL,
    "clientUserId" TEXT NOT NULL,
    "caseId" TEXT,
    "matterId" TEXT,
    "direction" "MessageDirection" NOT NULL,
    "subject" TEXT,
    "body" TEXT NOT NULL,
    "isRead" BOOLEAN NOT NULL DEFAULT false,
    "readAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "communication_records" (
    "id" TEXT NOT NULL,
    "type" "CommunicationType" NOT NULL,
    "subject" TEXT,
    "body" TEXT,
    "fromAddress" TEXT,
    "toAddresses" JSONB,
    "caseId" TEXT,
    "matterId" TEXT,
    "clientId" TEXT,
    "taskId" TEXT,
    "deadlineId" TEXT,
    "status" "CommunicationStatus" NOT NULL DEFAULT 'LOGGED',
    "direction" "CommunicationDirection" NOT NULL DEFAULT 'OUTBOUND',
    "occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "externalRef" TEXT,
    "metadata" JSONB,
    "createdBy" TEXT NOT NULL,

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

-- CreateTable
CREATE TABLE "local_outbox_entries" (
    "id" TEXT NOT NULL,
    "channel" TEXT NOT NULL,
    "recipient" TEXT NOT NULL,
    "subject" TEXT,
    "body" TEXT NOT NULL,
    "metadata" JSONB,
    "status" "OutboxStatus" NOT NULL DEFAULT 'PENDING',
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "sentAt" TIMESTAMP(3),
    "error" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "background_jobs" (
    "id" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "payload" JSONB,
    "status" "JobStatus" NOT NULL DEFAULT 'PENDING',
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "maxAttempts" INTEGER NOT NULL DEFAULT 3,
    "runAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "startedAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),
    "failedAt" TIMESTAMP(3),
    "error" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "saved_reports" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "type" TEXT NOT NULL,
    "filters" JSONB,
    "createdBy" TEXT NOT NULL,
    "isShared" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX "calendar_events_taskId_key" ON "calendar_events"("taskId");

-- CreateIndex
CREATE UNIQUE INDEX "calendar_events_deadlineId_key" ON "calendar_events"("deadlineId");

-- CreateIndex
CREATE INDEX "calendar_events_caseId_startAt_idx" ON "calendar_events"("caseId", "startAt");

-- CreateIndex
CREATE INDEX "calendar_events_assignedTo_startAt_idx" ON "calendar_events"("assignedTo", "startAt");

-- CreateIndex
CREATE INDEX "calendar_events_startAt_status_idx" ON "calendar_events"("startAt", "status");

-- CreateIndex
CREATE INDEX "notifications_userId_isRead_deliveredAt_idx" ON "notifications"("userId", "isRead", "deliveredAt");

-- CreateIndex
CREATE INDEX "notifications_entityType_entityId_idx" ON "notifications"("entityType", "entityId");

-- CreateIndex
CREATE INDEX "document_versions_documentId_isCurrent_idx" ON "document_versions"("documentId", "isCurrent");

-- CreateIndex
CREATE UNIQUE INDEX "document_versions_documentId_versionNumber_key" ON "document_versions"("documentId", "versionNumber");

-- CreateIndex
CREATE UNIQUE INDEX "commercial_workspaces_caseId_key" ON "commercial_workspaces"("caseId");

-- CreateIndex
CREATE INDEX "commercial_workspaces_workspaceType_idx" ON "commercial_workspaces"("workspaceType");

-- CreateIndex
CREATE INDEX "vendors_name_idx" ON "vendors"("name");

-- CreateIndex
CREATE UNIQUE INDEX "vendor_bills_billNumber_key" ON "vendor_bills"("billNumber");

-- CreateIndex
CREATE UNIQUE INDEX "vendor_bills_journalId_key" ON "vendor_bills"("journalId");

-- CreateIndex
CREATE INDEX "vendor_bills_vendorId_status_idx" ON "vendor_bills"("vendorId", "status");

-- CreateIndex
CREATE INDEX "vendor_bills_caseId_status_idx" ON "vendor_bills"("caseId", "status");

-- CreateIndex
CREATE UNIQUE INDEX "client_bank_accounts_accountNumber_key" ON "client_bank_accounts"("accountNumber");

-- CreateIndex
CREATE INDEX "client_ledger_entries_clientId_createdAt_idx" ON "client_ledger_entries"("clientId", "createdAt");

-- CreateIndex
CREATE INDEX "client_ledger_entries_caseId_createdAt_idx" ON "client_ledger_entries"("caseId", "createdAt");

-- CreateIndex
CREATE INDEX "client_ledger_entries_clientBankAccountId_createdAt_idx" ON "client_ledger_entries"("clientBankAccountId", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "client_receipts_journalId_key" ON "client_receipts"("journalId");

-- CreateIndex
CREATE INDEX "client_receipts_clientId_status_idx" ON "client_receipts"("clientId", "status");

-- CreateIndex
CREATE INDEX "client_receipts_caseId_status_idx" ON "client_receipts"("caseId", "status");

-- CreateIndex
CREATE INDEX "retainers_clientId_status_idx" ON "retainers"("clientId", "status");

-- CreateIndex
CREATE INDEX "retainers_caseId_idx" ON "retainers"("caseId");

-- CreateIndex
CREATE INDEX "judgments_caseId_status_idx" ON "judgments"("caseId", "status");

-- CreateIndex
CREATE INDEX "execution_activities_judgmentId_status_idx" ON "execution_activities"("judgmentId", "status");

-- CreateIndex
CREATE INDEX "settlements_caseId_status_idx" ON "settlements"("caseId", "status");

-- CreateIndex
CREATE INDEX "settlement_offers_settlementId_status_idx" ON "settlement_offers"("settlementId", "status");

-- CreateIndex
CREATE UNIQUE INDEX "remittances_caseId_key" ON "remittances"("caseId");

-- CreateIndex
CREATE UNIQUE INDEX "remittances_settlementId_key" ON "remittances"("settlementId");

-- CreateIndex
CREATE INDEX "remittances_caseId_status_idx" ON "remittances"("caseId", "status");

-- CreateIndex
CREATE UNIQUE INDEX "client_users_userId_key" ON "client_users"("userId");

-- CreateIndex
CREATE INDEX "client_users_clientId_idx" ON "client_users"("clientId");

-- CreateIndex
CREATE INDEX "portal_authorizations_entityType_entityId_idx" ON "portal_authorizations"("entityType", "entityId");

-- CreateIndex
CREATE UNIQUE INDEX "portal_authorizations_clientUserId_entityType_entityId_key" ON "portal_authorizations"("clientUserId", "entityType", "entityId");

-- CreateIndex
CREATE INDEX "portal_messages_clientUserId_createdAt_idx" ON "portal_messages"("clientUserId", "createdAt");

-- CreateIndex
CREATE INDEX "portal_messages_caseId_idx" ON "portal_messages"("caseId");

-- CreateIndex
CREATE INDEX "communication_records_caseId_occurredAt_idx" ON "communication_records"("caseId", "occurredAt");

-- CreateIndex
CREATE INDEX "communication_records_clientId_occurredAt_idx" ON "communication_records"("clientId", "occurredAt");

-- CreateIndex
CREATE INDEX "communication_records_type_status_idx" ON "communication_records"("type", "status");

-- CreateIndex
CREATE INDEX "local_outbox_entries_status_createdAt_idx" ON "local_outbox_entries"("status", "createdAt");

-- CreateIndex
CREATE INDEX "background_jobs_status_runAt_idx" ON "background_jobs"("status", "runAt");

-- CreateIndex
CREATE INDEX "background_jobs_type_status_idx" ON "background_jobs"("type", "status");

-- CreateIndex
CREATE INDEX "saved_reports_createdBy_idx" ON "saved_reports"("createdBy");

-- CreateIndex
CREATE INDEX "saved_reports_type_idx" ON "saved_reports"("type");

-- AddForeignKey
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_taskId_fkey" FOREIGN KEY ("taskId") REFERENCES "tasks"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_deadlineId_fkey" FOREIGN KEY ("deadlineId") REFERENCES "deadlines"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "calendar_events" ADD CONSTRAINT "calendar_events_assignedTo_fkey" FOREIGN KEY ("assignedTo") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "document_versions" ADD CONSTRAINT "document_versions_documentId_fkey" FOREIGN KEY ("documentId") REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "document_versions" ADD CONSTRAINT "document_versions_uploadedBy_fkey" FOREIGN KEY ("uploadedBy") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "commercial_workspaces" ADD CONSTRAINT "commercial_workspaces_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "vendor_bills" ADD CONSTRAINT "vendor_bills_vendorId_fkey" FOREIGN KEY ("vendorId") REFERENCES "vendors"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "vendor_bills" ADD CONSTRAINT "vendor_bills_journalId_fkey" FOREIGN KEY ("journalId") REFERENCES "journals"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_ledger_entries" ADD CONSTRAINT "client_ledger_entries_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "clients"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_ledger_entries" ADD CONSTRAINT "client_ledger_entries_clientBankAccountId_fkey" FOREIGN KEY ("clientBankAccountId") REFERENCES "client_bank_accounts"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_receipts" ADD CONSTRAINT "client_receipts_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "clients"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_receipts" ADD CONSTRAINT "client_receipts_clientBankAccountId_fkey" FOREIGN KEY ("clientBankAccountId") REFERENCES "client_bank_accounts"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_receipts" ADD CONSTRAINT "client_receipts_journalId_fkey" FOREIGN KEY ("journalId") REFERENCES "journals"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "retainers" ADD CONSTRAINT "retainers_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "clients"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "judgments" ADD CONSTRAINT "judgments_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "execution_activities" ADD CONSTRAINT "execution_activities_judgmentId_fkey" FOREIGN KEY ("judgmentId") REFERENCES "judgments"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "settlements" ADD CONSTRAINT "settlements_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "settlements" ADD CONSTRAINT "settlements_judgmentId_fkey" FOREIGN KEY ("judgmentId") REFERENCES "judgments"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "settlement_offers" ADD CONSTRAINT "settlement_offers_settlementId_fkey" FOREIGN KEY ("settlementId") REFERENCES "settlements"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "remittances" ADD CONSTRAINT "remittances_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "remittances" ADD CONSTRAINT "remittances_settlementId_fkey" FOREIGN KEY ("settlementId") REFERENCES "settlements"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_users" ADD CONSTRAINT "client_users_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "client_users" ADD CONSTRAINT "client_users_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "clients"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "portal_authorizations" ADD CONSTRAINT "portal_authorizations_clientUserId_fkey" FOREIGN KEY ("clientUserId") REFERENCES "client_users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "portal_messages" ADD CONSTRAINT "portal_messages_clientUserId_fkey" FOREIGN KEY ("clientUserId") REFERENCES "client_users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "communication_records" ADD CONSTRAINT "communication_records_caseId_fkey" FOREIGN KEY ("caseId") REFERENCES "cases"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "communication_records" ADD CONSTRAINT "communication_records_matterId_fkey" FOREIGN KEY ("matterId") REFERENCES "matters"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "communication_records" ADD CONSTRAINT "communication_records_clientId_fkey" FOREIGN KEY ("clientId") REFERENCES "clients"("id") ON DELETE SET NULL ON UPDATE CASCADE;
