import type { Knex } from 'knex';
import * as bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid';
import { ethers } from 'ethers';
import * as crypto from 'crypto';

// Simple encryption for demo purposes (in production use proper key management)
const ENCRYPTION_KEY = process.env.WALLET_ENCRYPTION_KEY || 'goa-gel-demo-encryption-key-32b';

function encryptPrivateKey(privateKey: string): string {
  const iv = crypto.randomBytes(16);
  const key = crypto.scryptSync(ENCRYPTION_KEY, 'salt', 32);
  const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  let encrypted = cipher.update(privateKey, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return iv.toString('hex') + ':' + encrypted;
}

function generateWallet(): { address: string; encryptedPrivateKey: string } {
  const wallet = ethers.Wallet.createRandom();
  return {
    address: wallet.address,
    encryptedPrivateKey: encryptPrivateKey(wallet.privateKey),
  };
}

// Helper to generate realistic dates spread over the last 30 days
function randomDate(daysAgo: number = 30): Date {
  const now = new Date();
  const randomDays = Math.floor(Math.random() * daysAgo);
  const randomHours = Math.floor(Math.random() * 24);
  const randomMinutes = Math.floor(Math.random() * 60);
  return new Date(
    now.getTime() -
      randomDays * 24 * 60 * 60 * 1000 -
      randomHours * 60 * 60 * 1000 -
      randomMinutes * 60 * 1000,
  );
}

// Helper to generate sequential dates for workflow progression
function sequentialDate(baseDate: Date, hoursLater: number): Date {
  return new Date(baseDate.getTime() + hoursLater * 60 * 60 * 1000);
}

// Helper to generate fake blockchain transaction hash
function fakeTxHash(): string {
  return '0x' + crypto.randomBytes(32).toString('hex');
}

// Helper to generate fake document hash
function fakeDocHash(): string {
  return '0x' + crypto.randomBytes(32).toString('hex');
}

export async function seed(knex: Knex): Promise<void> {
  // Clear existing data (in reverse order of dependencies)
  await knex('application_logs')
    .del()
    .catch(() => {});
  await knex('blockchain_events')
    .del()
    .catch(() => {});
  await knex('blockchain_transactions')
    .del()
    .catch(() => {});
  await knex('audit_logs')
    .del()
    .catch(() => {});
  await knex('webhook_logs')
    .del()
    .catch(() => {});
  await knex('wallets')
    .del()
    .catch(() => {});
  await knex('users')
    .del()
    .catch(() => {});
  await knex('approvals').del();
  await knex('workflow_states').del();
  await knex('document_versions').del();
  await knex('documents').del();
  await knex('license_requests').del();
  await knex('webhooks').del();
  await knex('workflows').del();
  await knex('departments').del();
  await knex('applicants').del();

  // ============================================
  // DEPARTMENTS (5 Goa Government Departments)
  // ============================================
  const transportDeptWallet = generateWallet();
  const revenueDeptWallet = generateWallet();
  const policeDeptWallet = generateWallet();
  const tourismDeptWallet = generateWallet();
  const healthDeptWallet = generateWallet();
  const fireDeptWallet = generateWallet();
  const municipalityWallet = generateWallet();

  const transportDeptId = uuidv4();
  const revenueDeptId = uuidv4();
  const policeDeptId = uuidv4();
  const tourismDeptId = uuidv4();
  const healthDeptId = uuidv4();
  const fireDeptId = uuidv4();
  const municipalityId = uuidv4();

  const departments = [
    {
      id: transportDeptId,
      code: 'TRANSPORT_DEPT',
      name: 'Directorate of Transport, Goa',
      wallet_address: transportDeptWallet.address,
      api_key_hash: await bcrypt.hash('transport_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('transport_secret_456', 10),
      is_active: true,
      description: 'Handles vehicle registration, driving licenses, and transport permits in Goa',
      contact_email: 'transport@goa.gov.in',
      contact_phone: '+91-832-2438801',
    },
    {
      id: revenueDeptId,
      code: 'REVENUE_DEPT',
      name: 'Directorate of Land Revenue, Goa',
      wallet_address: revenueDeptWallet.address,
      api_key_hash: await bcrypt.hash('revenue_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('revenue_secret_456', 10),
      is_active: true,
      description: 'Manages land records, property registration, and revenue collection',
      contact_email: 'revenue@goa.gov.in',
      contact_phone: '+91-832-2225566',
    },
    {
      id: policeDeptId,
      code: 'POLICE_DEPT',
      name: 'Goa Police Department',
      wallet_address: policeDeptWallet.address,
      api_key_hash: await bcrypt.hash('police_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('police_secret_456', 10),
      is_active: true,
      description: 'Law enforcement, character verification, and NOC issuance',
      contact_email: 'dgp@goapolice.gov.in',
      contact_phone: '+91-832-2418701',
    },
    {
      id: tourismDeptId,
      code: 'TOURISM_DEPT',
      name: 'Goa Tourism Development Corporation',
      wallet_address: tourismDeptWallet.address,
      api_key_hash: await bcrypt.hash('tourism_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('tourism_secret_456', 10),
      is_active: true,
      description: 'Promotes tourism, issues licenses for hotels, resorts, and tourism activities',
      contact_email: 'tourism@goa.gov.in',
      contact_phone: '+91-832-2437132',
    },
    {
      id: healthDeptId,
      code: 'HEALTH_DEPT',
      name: 'Directorate of Health Services, Goa',
      wallet_address: healthDeptWallet.address,
      api_key_hash: await bcrypt.hash('health_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('health_secret_456', 10),
      is_active: true,
      description: 'Health inspections, sanitation certificates, and medical licenses',
      contact_email: 'health@goa.gov.in',
      contact_phone: '+91-832-2225736',
    },
    {
      id: fireDeptId,
      code: 'FIRE_DEPT',
      name: 'Goa Fire & Emergency Services',
      wallet_address: fireDeptWallet.address,
      api_key_hash: await bcrypt.hash('fire_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('fire_secret_456', 10),
      is_active: true,
      description: 'Fire safety inspections and NOC issuance for commercial establishments',
      contact_email: 'fire@goa.gov.in',
      contact_phone: '+91-832-2222222',
    },
    {
      id: municipalityId,
      code: 'MUNICIPALITY',
      name: 'Corporation of the City of Panaji',
      wallet_address: municipalityWallet.address,
      api_key_hash: await bcrypt.hash('municipality_api_key_123', 10),
      api_secret_hash: await bcrypt.hash('municipality_secret_456', 10),
      is_active: true,
      description: 'Local governance, building permits, trade licenses, and property tax',
      contact_email: 'ccpanaji@goa.gov.in',
      contact_phone: '+91-832-2426516',
    },
  ];

  await knex('departments').insert(departments);

  // Store department wallets
  const departmentWallets = [
    {
      ...transportDeptWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: transportDeptId,
      is_active: true,
    },
    {
      ...revenueDeptWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: revenueDeptId,
      is_active: true,
    },
    {
      ...policeDeptWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: policeDeptId,
      is_active: true,
    },
    {
      ...tourismDeptWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: tourismDeptId,
      is_active: true,
    },
    {
      ...healthDeptWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: healthDeptId,
      is_active: true,
    },
    {
      ...fireDeptWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: fireDeptId,
      is_active: true,
    },
    {
      ...municipalityWallet,
      id: uuidv4(),
      owner_type: 'DEPARTMENT',
      owner_id: municipalityId,
      is_active: true,
    },
  ].map(w => ({
    id: w.id,
    address: w.address,
    encrypted_private_key: w.encryptedPrivateKey,
    owner_type: w.owner_type,
    owner_id: w.owner_id,
    is_active: w.is_active,
  }));

  await knex('wallets').insert(departmentWallets);

  // ============================================
  // USERS (Admin + Department Users)
  // ============================================
  const adminWallet = generateWallet();
  const transportUserWallet = generateWallet();
  const revenueUserWallet = generateWallet();
  const policeUserWallet = generateWallet();
  const tourismUserWallet = generateWallet();
  const healthUserWallet = generateWallet();
  const fireUserWallet = generateWallet();
  const municipalityUserWallet = generateWallet();

  const adminUserId = uuidv4();
  const transportUserId = uuidv4();
  const revenueUserId = uuidv4();
  const policeUserId = uuidv4();
  const tourismUserId = uuidv4();
  const healthUserId = uuidv4();
  const fireUserId = uuidv4();
  const municipalityUserId = uuidv4();

  // Generate citizen wallets
  const citizenWallets: { id: string; wallet: ReturnType<typeof generateWallet> }[] = [];
  for (let i = 0; i < 12; i++) {
    citizenWallets.push({ id: uuidv4(), wallet: generateWallet() });
  }

  const users = [
    {
      id: adminUserId,
      email: 'admin@goa.gov.in',
      password_hash: await bcrypt.hash('Admin@123', 10),
      name: 'Dr. Pramod Sawant',
      role: 'ADMIN',
      department_id: null,
      wallet_address: adminWallet.address,
      wallet_encrypted_key: adminWallet.encryptedPrivateKey,
      phone: '+91-9876543210',
      is_active: true,
    },
    {
      id: transportUserId,
      email: 'transport@goa.gov.in',
      password_hash: await bcrypt.hash('Transport@123', 10),
      name: 'Shri Ravi Naik',
      role: 'DEPARTMENT',
      department_id: transportDeptId,
      wallet_address: transportUserWallet.address,
      wallet_encrypted_key: transportUserWallet.encryptedPrivateKey,
      phone: '+91-9876543211',
      is_active: true,
    },
    {
      id: revenueUserId,
      email: 'revenue@goa.gov.in',
      password_hash: await bcrypt.hash('Revenue@123', 10),
      name: 'Smt. Priya Tendulkar',
      role: 'DEPARTMENT',
      department_id: revenueDeptId,
      wallet_address: revenueUserWallet.address,
      wallet_encrypted_key: revenueUserWallet.encryptedPrivateKey,
      phone: '+91-9876543212',
      is_active: true,
    },
    {
      id: policeUserId,
      email: 'police@goa.gov.in',
      password_hash: await bcrypt.hash('Police@123', 10),
      name: 'IPS Jaspal Singh',
      role: 'DEPARTMENT',
      department_id: policeDeptId,
      wallet_address: policeUserWallet.address,
      wallet_encrypted_key: policeUserWallet.encryptedPrivateKey,
      phone: '+91-9876543213',
      is_active: true,
    },
    {
      id: tourismUserId,
      email: 'tourism@goa.gov.in',
      password_hash: await bcrypt.hash('Tourism@123', 10),
      name: 'Shri Rohan Khaunte',
      role: 'DEPARTMENT',
      department_id: tourismDeptId,
      wallet_address: tourismUserWallet.address,
      wallet_encrypted_key: tourismUserWallet.encryptedPrivateKey,
      phone: '+91-9876543214',
      is_active: true,
    },
    {
      id: healthUserId,
      email: 'health@goa.gov.in',
      password_hash: await bcrypt.hash('Health@123', 10),
      name: 'Dr. Vishwajit Rane',
      role: 'DEPARTMENT',
      department_id: healthDeptId,
      wallet_address: healthUserWallet.address,
      wallet_encrypted_key: healthUserWallet.encryptedPrivateKey,
      phone: '+91-9876543215',
      is_active: true,
    },
    {
      id: fireUserId,
      email: 'fire@goa.gov.in',
      password_hash: await bcrypt.hash('Fire@123', 10),
      name: 'Shri Ashok Menon',
      role: 'DEPARTMENT',
      department_id: fireDeptId,
      wallet_address: fireUserWallet.address,
      wallet_encrypted_key: fireUserWallet.encryptedPrivateKey,
      phone: '+91-9876543216',
      is_active: true,
    },
    {
      id: municipalityUserId,
      email: 'municipality@goa.gov.in',
      password_hash: await bcrypt.hash('Municipality@123', 10),
      name: 'Smt. Babita Shirodkar',
      role: 'DEPARTMENT',
      department_id: municipalityId,
      wallet_address: municipalityUserWallet.address,
      wallet_encrypted_key: municipalityUserWallet.encryptedPrivateKey,
      phone: '+91-9876543217',
      is_active: true,
    },
    // Citizen users
    {
      id: citizenWallets[0].id,
      email: 'rajesh.naik@example.com',
      password_hash: await bcrypt.hash('Citizen@123', 10),
      name: 'Rajesh Vishnu Naik',
      role: 'CITIZEN',
      department_id: null,
      wallet_address: citizenWallets[0].wallet.address,
      wallet_encrypted_key: citizenWallets[0].wallet.encryptedPrivateKey,
      phone: '+91-9823456789',
      is_active: true,
    },
    {
      id: citizenWallets[1].id,
      email: 'priya.kamat@example.com',
      password_hash: await bcrypt.hash('Citizen@123', 10),
      name: 'Priya Shankar Kamat',
      role: 'CITIZEN',
      department_id: null,
      wallet_address: citizenWallets[1].wallet.address,
      wallet_encrypted_key: citizenWallets[1].wallet.encryptedPrivateKey,
      phone: '+91-9823456790',
      is_active: true,
    },
    {
      id: citizenWallets[2].id,
      email: 'antonio.fernandes@example.com',
      password_hash: await bcrypt.hash('Citizen@123', 10),
      name: 'Antonio Jose Fernandes',
      role: 'CITIZEN',
      department_id: null,
      wallet_address: citizenWallets[2].wallet.address,
      wallet_encrypted_key: citizenWallets[2].wallet.encryptedPrivateKey,
      phone: '+91-9823456791',
      is_active: true,
    },
    {
      id: citizenWallets[3].id,
      email: 'sunita.desai@example.com',
      password_hash: await bcrypt.hash('Citizen@123', 10),
      name: 'Sunita Ramesh Desai',
      role: 'CITIZEN',
      department_id: null,
      wallet_address: citizenWallets[3].wallet.address,
      wallet_encrypted_key: citizenWallets[3].wallet.encryptedPrivateKey,
      phone: '+91-9823456792',
      is_active: true,
    },
  ];

  await knex('users').insert(users);

  // Store user wallets
  const userWallets = [
    { ...adminWallet, id: uuidv4(), owner_type: 'USER', owner_id: adminUserId, is_active: true },
    {
      ...transportUserWallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: transportUserId,
      is_active: true,
    },
    {
      ...revenueUserWallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: revenueUserId,
      is_active: true,
    },
    {
      ...policeUserWallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: policeUserId,
      is_active: true,
    },
    {
      ...tourismUserWallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: tourismUserId,
      is_active: true,
    },
    {
      ...healthUserWallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: healthUserId,
      is_active: true,
    },
    { ...fireUserWallet, id: uuidv4(), owner_type: 'USER', owner_id: fireUserId, is_active: true },
    {
      ...municipalityUserWallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: municipalityUserId,
      is_active: true,
    },
    ...citizenWallets.slice(0, 4).map(c => ({
      ...c.wallet,
      id: uuidv4(),
      owner_type: 'USER',
      owner_id: c.id,
      is_active: true,
    })),
  ].map(w => ({
    id: w.id,
    address: w.address,
    encrypted_private_key: w.encryptedPrivateKey,
    owner_type: w.owner_type,
    owner_id: w.owner_id,
    is_active: w.is_active,
  }));

  await knex('wallets').insert(userWallets);

  // ============================================
  // APPLICANTS (12 realistic Goan names)
  // ============================================
  const applicants = [
    {
      id: citizenWallets[0].id,
      digilocker_id: 'DL-GOA-2024-001',
      name: 'Rajesh Vishnu Naik',
      email: 'rajesh.naik@example.com',
      phone: '+91-9823456789',
      wallet_address: citizenWallets[0].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[1].id,
      digilocker_id: 'DL-GOA-2024-002',
      name: 'Priya Shankar Kamat',
      email: 'priya.kamat@example.com',
      phone: '+91-9823456790',
      wallet_address: citizenWallets[1].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[2].id,
      digilocker_id: 'DL-GOA-2024-003',
      name: 'Antonio Jose Fernandes',
      email: 'antonio.fernandes@example.com',
      phone: '+91-9823456791',
      wallet_address: citizenWallets[2].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[3].id,
      digilocker_id: 'DL-GOA-2024-004',
      name: 'Sunita Ramesh Desai',
      email: 'sunita.desai@example.com',
      phone: '+91-9823456792',
      wallet_address: citizenWallets[3].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[4].id,
      digilocker_id: 'DL-GOA-2024-005',
      name: "Francisco Xavier D'Souza",
      email: 'francisco.dsouza@example.com',
      phone: '+91-9823456793',
      wallet_address: citizenWallets[4].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[5].id,
      digilocker_id: 'DL-GOA-2024-006',
      name: 'Mangesh Pramod Shirodkar',
      email: 'mangesh.shirodkar@example.com',
      phone: '+91-9823456794',
      wallet_address: citizenWallets[5].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[6].id,
      digilocker_id: 'DL-GOA-2024-007',
      name: 'Maria Conceicao Pereira',
      email: 'maria.pereira@example.com',
      phone: '+91-9823456795',
      wallet_address: citizenWallets[6].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[7].id,
      digilocker_id: 'DL-GOA-2024-008',
      name: 'Vitthal Ganesh Prabhu',
      email: 'vitthal.prabhu@example.com',
      phone: '+91-9823456796',
      wallet_address: citizenWallets[7].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[8].id,
      digilocker_id: 'DL-GOA-2024-009',
      name: 'Anjali Mohan Naik',
      email: 'anjali.naik@example.com',
      phone: '+91-9823456797',
      wallet_address: citizenWallets[8].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[9].id,
      digilocker_id: 'DL-GOA-2024-010',
      name: 'Peter Anthony Rodrigues',
      email: 'peter.rodrigues@example.com',
      phone: '+91-9823456798',
      wallet_address: citizenWallets[9].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[10].id,
      digilocker_id: 'DL-GOA-2024-011',
      name: 'Deepa Narayan Phadte',
      email: 'deepa.phadte@example.com',
      phone: '+91-9823456799',
      wallet_address: citizenWallets[10].wallet.address,
      is_active: true,
    },
    {
      id: citizenWallets[11].id,
      digilocker_id: 'DL-GOA-2024-012',
      name: 'Anand Krishna Shetgaonkar',
      email: 'anand.shetgaonkar@example.com',
      phone: '+91-9823456800',
      wallet_address: citizenWallets[11].wallet.address,
      is_active: true,
    },
  ];

  await knex('applicants').insert(applicants);

  // ============================================
  // WORKFLOWS (5 different workflow types)
  // ============================================
  const resortLicenseWorkflowId = uuidv4();
  const tradeLicenseWorkflowId = uuidv4();
  const buildingPermitWorkflowId = uuidv4();
  const fireSafetyCertWorkflowId = uuidv4();
  const healthCertWorkflowId = uuidv4();

  const workflows = [
    {
      id: resortLicenseWorkflowId,
      workflow_type: 'RESORT_LICENSE',
      name: 'Resort/Hotel License Approval Workflow',
      description:
        'Multi-department approval workflow for resort and hotel licenses in Goa. Requires fire safety, tourism, municipality, and health clearances.',
      version: 1,
      definition: JSON.stringify({
        isActive: true,
        stages: [
          {
            stageId: 'stage_1_fire',
            stageName: 'Fire Safety Inspection',
            stageOrder: 1,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'FIRE_DEPT',
                departmentName: 'Goa Fire & Emergency Services',
                requiredDocuments: ['FIRE_SAFETY_CERTIFICATE', 'BUILDING_PLAN'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 7,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
          {
            stageId: 'stage_2_parallel',
            stageName: 'Tourism & Municipality Review',
            stageOrder: 2,
            executionType: 'PARALLEL',
            requiredApprovals: [
              {
                departmentCode: 'TOURISM_DEPT',
                departmentName: 'Goa Tourism Development Corporation',
                requiredDocuments: ['PROPERTY_OWNERSHIP', 'BUILDING_PLAN'],
                isMandatory: true,
              },
              {
                departmentCode: 'MUNICIPALITY',
                departmentName: 'Corporation of the City of Panaji',
                requiredDocuments: ['PROPERTY_OWNERSHIP', 'TAX_CLEARANCE'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 14,
            onTimeout: 'ESCALATE',
            onRejection: 'FAIL_REQUEST',
          },
          {
            stageId: 'stage_3_health',
            stageName: 'Health & Sanitation Clearance',
            stageOrder: 3,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'HEALTH_DEPT',
                departmentName: 'Directorate of Health Services, Goa',
                requiredDocuments: ['HEALTH_CERTIFICATE'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 7,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
        ],
      }),
      is_active: true,
    },
    {
      id: tradeLicenseWorkflowId,
      workflow_type: 'TRADE_LICENSE',
      name: 'Trade License Approval Workflow',
      description: 'Workflow for issuing trade licenses to commercial establishments in Goa',
      version: 1,
      definition: JSON.stringify({
        isActive: true,
        stages: [
          {
            stageId: 'stage_1_municipality',
            stageName: 'Municipal Verification',
            stageOrder: 1,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'MUNICIPALITY',
                departmentName: 'Corporation of the City of Panaji',
                requiredDocuments: ['PROPERTY_OWNERSHIP', 'TAX_CLEARANCE', 'IDENTITY_PROOF'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 10,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
          {
            stageId: 'stage_2_fire',
            stageName: 'Fire Safety Verification',
            stageOrder: 2,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'FIRE_DEPT',
                departmentName: 'Goa Fire & Emergency Services',
                requiredDocuments: ['FIRE_SAFETY_CERTIFICATE'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 7,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
        ],
      }),
      is_active: true,
    },
    {
      id: buildingPermitWorkflowId,
      workflow_type: 'BUILDING_PERMIT',
      name: 'Building Permit Approval Workflow',
      description: 'Multi-stage workflow for construction and building permits in Goa',
      version: 1,
      definition: JSON.stringify({
        isActive: true,
        stages: [
          {
            stageId: 'stage_1_revenue',
            stageName: 'Land Verification',
            stageOrder: 1,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'REVENUE_DEPT',
                departmentName: 'Directorate of Land Revenue, Goa',
                requiredDocuments: ['PROPERTY_OWNERSHIP', 'IDENTITY_PROOF'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 10,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
          {
            stageId: 'stage_2_municipality',
            stageName: 'Building Plan Approval',
            stageOrder: 2,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'MUNICIPALITY',
                departmentName: 'Corporation of the City of Panaji',
                requiredDocuments: ['BUILDING_PLAN', 'ENVIRONMENTAL_CLEARANCE'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 14,
            onTimeout: 'ESCALATE',
            onRejection: 'FAIL_REQUEST',
          },
          {
            stageId: 'stage_3_fire',
            stageName: 'Fire Safety Plan Review',
            stageOrder: 3,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'FIRE_DEPT',
                departmentName: 'Goa Fire & Emergency Services',
                requiredDocuments: ['FIRE_SAFETY_CERTIFICATE', 'BUILDING_PLAN'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 7,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
        ],
      }),
      is_active: true,
    },
    {
      id: fireSafetyCertWorkflowId,
      workflow_type: 'FIRE_SAFETY_CERT',
      name: 'Fire Safety Certificate Workflow',
      description: 'Simplified fire safety certificate approval workflow',
      version: 1,
      definition: JSON.stringify({
        isActive: true,
        stages: [
          {
            stageId: 'stage_1_fire',
            stageName: 'Fire Safety Review',
            stageOrder: 1,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'FIRE_DEPT',
                departmentName: 'Goa Fire & Emergency Services',
                requiredDocuments: ['FIRE_SAFETY_CERTIFICATE', 'BUILDING_PLAN'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 7,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
        ],
      }),
      is_active: true,
    },
    {
      id: healthCertWorkflowId,
      workflow_type: 'HEALTH_CERT',
      name: 'Health & Sanitation Certificate Workflow',
      description: 'Workflow for health and sanitation certificates for food establishments',
      version: 1,
      definition: JSON.stringify({
        isActive: true,
        stages: [
          {
            stageId: 'stage_1_health',
            stageName: 'Health Inspection',
            stageOrder: 1,
            executionType: 'SEQUENTIAL',
            requiredApprovals: [
              {
                departmentCode: 'HEALTH_DEPT',
                departmentName: 'Directorate of Health Services, Goa',
                requiredDocuments: ['HEALTH_CERTIFICATE', 'IDENTITY_PROOF'],
                isMandatory: true,
              },
            ],
            completionCriteria: 'ALL',
            timeoutDays: 7,
            onTimeout: 'NOTIFY',
            onRejection: 'FAIL_REQUEST',
          },
        ],
      }),
      is_active: true,
    },
  ];

  await knex('workflows').insert(workflows);

  // ============================================
  // LICENSE REQUESTS (25 requests in various statuses)
  // ============================================
  const licenseRequests: any[] = [];
  const documents: any[] = [];
  const documentVersions: any[] = [];
  const approvals: any[] = [];
  const workflowStates: any[] = [];
  const auditLogs: any[] = [];
  const blockchainTransactions: any[] = [];

  // Helper function to create a complete license request with documents and approvals
  const createLicenseRequest = (
    applicantId: string,
    applicantName: string,
    requestType: string,
    workflowId: string,
    status: string,
    metadata: any,
    requestNumber: string,
    createdDate: Date,
    departments: { id: string; status: string; remarks?: string }[],
    currentStageId: string,
  ) => {
    const requestId = uuidv4();
    const submittedAt = status !== 'DRAFT' ? sequentialDate(createdDate, 1) : null;
    const approvedAt = status === 'APPROVED' ? sequentialDate(createdDate, 72) : null;
    const tokenId = status === 'APPROVED' ? Math.floor(Math.random() * 10000) + 1 : null;

    // Create the license request
    licenseRequests.push({
      id: requestId,
      request_number: requestNumber,
      token_id: tokenId,
      applicant_id: applicantId,
      request_type: requestType,
      workflow_id: workflowId,
      status,
      metadata: JSON.stringify(metadata),
      current_stage_id: currentStageId,
      blockchain_tx_hash: status === 'APPROVED' ? fakeTxHash() : null,
      created_at: createdDate,
      updated_at: status !== 'DRAFT' ? submittedAt : createdDate,
      submitted_at: submittedAt,
      approved_at: approvedAt,
    });

    // Create documents for each request
    const docTypes = [
      'PROPERTY_OWNERSHIP',
      'FIRE_SAFETY_CERTIFICATE',
      'BUILDING_PLAN',
      'TAX_CLEARANCE',
    ];
    docTypes.forEach((docType, index) => {
      const docId = uuidv4();
      const docHash = fakeDocHash();
      documents.push({
        id: docId,
        request_id: requestId,
        doc_type: docType,
        original_filename: `${docType.toLowerCase().replace(/_/g, '-')}-${requestNumber}.pdf`,
        current_version: 1,
        current_hash: docHash,
        minio_bucket: 'goa-gel-documents',
        is_active: true,
        created_at: createdDate,
        updated_at: createdDate,
      });

      // Create document version
      const versionId = uuidv4();
      documentVersions.push({
        id: versionId,
        document_id: docId,
        version: 1,
        hash: docHash,
        minio_path: `documents/${requestId}/${docType.toLowerCase()}/${versionId}.pdf`,
        file_size: Math.floor(Math.random() * 5000000) + 100000,
        mime_type: 'application/pdf',
        uploaded_by: applicantId,
        blockchain_tx_hash: null,
        created_at: createdDate,
      });
    });

    // Create approvals for each department
    departments.forEach((dept, index) => {
      const approvalId = uuidv4();
      const approvalDate = sequentialDate(createdDate, (index + 1) * 24);
      approvals.push({
        id: approvalId,
        request_id: requestId,
        department_id: dept.id,
        status: dept.status,
        remarks: dept.remarks || null,
        remarks_hash: dept.remarks ? fakeDocHash() : null,
        reviewed_documents: JSON.stringify(['PROPERTY_OWNERSHIP', 'FIRE_SAFETY_CERTIFICATE']),
        blockchain_tx_hash: dept.status === 'APPROVED' ? fakeTxHash() : null,
        is_active: true,
        created_at: approvalDate,
        updated_at: approvalDate,
      });
    });

    // Create workflow state
    const completedStages =
      status === 'APPROVED'
        ? ['stage_1_fire', 'stage_2_parallel', 'stage_3_health']
        : status === 'IN_REVIEW' && currentStageId === 'stage_2_parallel'
          ? ['stage_1_fire']
          : [];

    workflowStates.push({
      id: uuidv4(),
      request_id: requestId,
      current_stage_id: currentStageId,
      completed_stages: JSON.stringify(completedStages),
      pending_approvals: JSON.stringify(
        departments.filter(d => d.status === 'PENDING').map(d => d.id),
      ),
      execution_log: JSON.stringify([
        {
          timestamp: createdDate.toISOString(),
          action: 'WORKFLOW_STARTED',
          stageId: 'stage_1_fire',
        },
      ]),
      stage_started_at: createdDate,
      created_at: createdDate,
      updated_at: status !== 'DRAFT' ? submittedAt : createdDate,
    });

    // Create audit log entries
    auditLogs.push({
      id: uuidv4(),
      entity_type: 'REQUEST',
      entity_id: requestId,
      action: 'CREATE',
      actor_type: 'APPLICANT',
      actor_id: applicantId,
      old_value: null,
      new_value: JSON.stringify({ status: 'DRAFT', requestNumber }),
      ip_address: '192.168.1.' + Math.floor(Math.random() * 254 + 1),
      user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      correlation_id: uuidv4(),
      created_at: createdDate,
    });

    if (status !== 'DRAFT') {
      auditLogs.push({
        id: uuidv4(),
        entity_type: 'REQUEST',
        entity_id: requestId,
        action: 'SUBMIT',
        actor_type: 'APPLICANT',
        actor_id: applicantId,
        old_value: JSON.stringify({ status: 'DRAFT' }),
        new_value: JSON.stringify({ status: 'SUBMITTED' }),
        ip_address: '192.168.1.' + Math.floor(Math.random() * 254 + 1),
        user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        correlation_id: uuidv4(),
        created_at: submittedAt,
      });
    }

    if (status === 'APPROVED') {
      auditLogs.push({
        id: uuidv4(),
        entity_type: 'REQUEST',
        entity_id: requestId,
        action: 'APPROVE',
        actor_type: 'SYSTEM',
        actor_id: null,
        old_value: JSON.stringify({ status: 'IN_REVIEW' }),
        new_value: JSON.stringify({ status: 'APPROVED', tokenId }),
        ip_address: null,
        user_agent: 'GEL-Backend-System',
        correlation_id: uuidv4(),
        created_at: approvedAt,
      });

      // Add blockchain transaction for approved requests
      blockchainTransactions.push({
        id: uuidv4(),
        tx_hash: fakeTxHash(),
        tx_type: 'MINT_NFT',
        related_entity_type: 'REQUEST',
        related_entity_id: requestId,
        from_address: citizenWallets[0].wallet.address,
        to_address: '0x' + crypto.randomBytes(20).toString('hex'),
        status: 'CONFIRMED',
        block_number: Math.floor(Math.random() * 1000000) + 1000000,
        gas_used: Math.floor(Math.random() * 500000) + 100000,
        error_message: null,
        created_at: approvedAt,
        confirmed_at: sequentialDate(approvedAt!, 0.1),
      });
    }

    if (status === 'REJECTED') {
      auditLogs.push({
        id: uuidv4(),
        entity_type: 'REQUEST',
        entity_id: requestId,
        action: 'REJECT',
        actor_type: 'DEPARTMENT',
        actor_id: departments[0].id,
        old_value: JSON.stringify({ status: 'IN_REVIEW' }),
        new_value: JSON.stringify({
          status: 'REJECTED',
          reason: 'Documents incomplete or invalid',
        }),
        ip_address: '10.0.0.' + Math.floor(Math.random() * 254 + 1),
        user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        correlation_id: uuidv4(),
        created_at: sequentialDate(createdDate, 48),
      });
    }

    return requestId;
  };

  // Create 25 license requests with various statuses
  // APPROVED (5)
  createLicenseRequest(
    applicants[0].id,
    applicants[0].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'APPROVED',
    {
      propertyName: 'Goa Beach Resort',
      location: 'Calangute Beach Road, Bardez',
      area: '5000 sqm',
      rooms: 50,
    },
    'GOA-RL-2024-0001',
    randomDate(28),
    [
      { id: fireDeptId, status: 'APPROVED', remarks: 'Fire safety measures are adequate' },
      { id: tourismDeptId, status: 'APPROVED', remarks: 'Tourism standards met' },
      { id: municipalityId, status: 'APPROVED', remarks: 'Building regulations compliant' },
      {
        id: healthDeptId,
        status: 'APPROVED',
        remarks: 'Health and sanitation requirements satisfied',
      },
    ],
    'stage_3_health',
  );

  createLicenseRequest(
    applicants[1].id,
    applicants[1].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'APPROVED',
    {
      businessName: 'Kamat Provisions Store',
      location: '18th June Road, Panaji',
      businessType: 'Retail - Groceries',
    },
    'GOA-TL-2024-0001',
    randomDate(25),
    [
      { id: municipalityId, status: 'APPROVED', remarks: 'All documents verified' },
      { id: fireDeptId, status: 'APPROVED', remarks: 'Fire extinguishers installed' },
    ],
    'stage_2_fire',
  );

  createLicenseRequest(
    applicants[2].id,
    applicants[2].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'APPROVED',
    {
      propertyName: 'Fernandes Villa Resort',
      location: 'Dona Paula Beach Road',
      area: '3500 sqm',
      rooms: 30,
    },
    'GOA-RL-2024-0002',
    randomDate(22),
    [
      { id: fireDeptId, status: 'APPROVED', remarks: 'Excellent fire safety compliance' },
      { id: tourismDeptId, status: 'APPROVED', remarks: 'Luxury category approved' },
      { id: municipalityId, status: 'APPROVED', remarks: 'Property tax cleared' },
      { id: healthDeptId, status: 'APPROVED', remarks: 'Kitchen and sanitation inspected' },
    ],
    'stage_3_health',
  );

  createLicenseRequest(
    applicants[3].id,
    applicants[3].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'APPROVED',
    { projectName: 'Desai Residency', location: 'Mapusa', floors: 4, builtUpArea: '1200 sqm' },
    'GOA-BP-2024-0001',
    randomDate(20),
    [
      { id: revenueDeptId, status: 'APPROVED', remarks: 'Land ownership verified' },
      { id: municipalityId, status: 'APPROVED', remarks: 'Building plan approved as per norms' },
      { id: fireDeptId, status: 'APPROVED', remarks: 'Fire staircase and exit plan approved' },
    ],
    'stage_3_fire',
  );

  createLicenseRequest(
    applicants[4].id,
    applicants[4].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'APPROVED',
    {
      businessName: "D'Souza Electronics",
      location: 'Margao Market',
      businessType: 'Retail - Electronics',
    },
    'GOA-TL-2024-0002',
    randomDate(18),
    [
      { id: municipalityId, status: 'APPROVED', remarks: 'Shop registration complete' },
      { id: fireDeptId, status: 'APPROVED', remarks: 'Electrical safety verified' },
    ],
    'stage_2_fire',
  );

  // IN_REVIEW (7)
  createLicenseRequest(
    applicants[5].id,
    applicants[5].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'IN_REVIEW',
    {
      propertyName: 'Shirodkar Beach Shacks',
      location: 'Anjuna Beach',
      area: '2000 sqm',
      rooms: 20,
    },
    'GOA-RL-2024-0003',
    randomDate(15),
    [
      { id: fireDeptId, status: 'APPROVED', remarks: 'Fire safety adequate for beach shack setup' },
      { id: tourismDeptId, status: 'PENDING' },
      { id: municipalityId, status: 'PENDING' },
    ],
    'stage_2_parallel',
  );

  createLicenseRequest(
    applicants[6].id,
    applicants[6].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'IN_REVIEW',
    {
      projectName: 'Pereira Commercial Complex',
      location: 'Vasco da Gama',
      floors: 6,
      builtUpArea: '3000 sqm',
    },
    'GOA-BP-2024-0002',
    randomDate(12),
    [
      { id: revenueDeptId, status: 'APPROVED', remarks: 'Land records clear' },
      { id: municipalityId, status: 'PENDING' },
    ],
    'stage_2_municipality',
  );

  createLicenseRequest(
    applicants[7].id,
    applicants[7].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'IN_REVIEW',
    { propertyName: 'Prabhu Heritage Resort', location: 'Old Goa', area: '4000 sqm', rooms: 35 },
    'GOA-RL-2024-0004',
    randomDate(10),
    [{ id: fireDeptId, status: 'PENDING' }],
    'stage_1_fire',
  );

  createLicenseRequest(
    applicants[8].id,
    applicants[8].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'IN_REVIEW',
    {
      businessName: 'Naik Restaurant',
      location: 'Panjim Bus Stand Area',
      businessType: 'Food & Beverage',
    },
    'GOA-TL-2024-0003',
    randomDate(8),
    [
      { id: municipalityId, status: 'APPROVED', remarks: 'Location approved for restaurant' },
      { id: fireDeptId, status: 'PENDING' },
    ],
    'stage_2_fire',
  );

  createLicenseRequest(
    applicants[9].id,
    applicants[9].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'IN_REVIEW',
    { propertyName: 'Rodrigues Beach Resort', location: 'Baga Beach', area: '6000 sqm', rooms: 60 },
    'GOA-RL-2024-0005',
    randomDate(7),
    [
      { id: fireDeptId, status: 'APPROVED', remarks: 'Fire hydrant system installed' },
      { id: tourismDeptId, status: 'APPROVED', remarks: '5-star category recommended' },
      { id: municipalityId, status: 'APPROVED', remarks: 'All clearances in order' },
      { id: healthDeptId, status: 'PENDING' },
    ],
    'stage_3_health',
  );

  createLicenseRequest(
    applicants[10].id,
    applicants[10].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'IN_REVIEW',
    { projectName: 'Phadte Apartments', location: 'Porvorim', floors: 5, builtUpArea: '2500 sqm' },
    'GOA-BP-2024-0003',
    randomDate(6),
    [{ id: revenueDeptId, status: 'PENDING' }],
    'stage_1_revenue',
  );

  createLicenseRequest(
    applicants[11].id,
    applicants[11].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'IN_REVIEW',
    {
      businessName: 'Shetgaonkar Auto Parts',
      location: 'Bicholim',
      businessType: 'Automotive Parts',
    },
    'GOA-TL-2024-0004',
    randomDate(5),
    [{ id: municipalityId, status: 'PENDING' }],
    'stage_1_municipality',
  );

  // SUBMITTED (5)
  createLicenseRequest(
    applicants[0].id,
    applicants[0].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'SUBMITTED',
    {
      businessName: 'Naik Pharmacy',
      location: 'Mapusa Market',
      businessType: 'Healthcare - Pharmacy',
    },
    'GOA-TL-2024-0005',
    randomDate(4),
    [{ id: municipalityId, status: 'PENDING' }],
    'stage_1_municipality',
  );

  createLicenseRequest(
    applicants[1].id,
    applicants[1].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'SUBMITTED',
    {
      projectName: 'Kamat Industrial Shed',
      location: 'Ponda Industrial Estate',
      floors: 1,
      builtUpArea: '500 sqm',
    },
    'GOA-BP-2024-0004',
    randomDate(3),
    [{ id: revenueDeptId, status: 'PENDING' }],
    'stage_1_revenue',
  );

  createLicenseRequest(
    applicants[2].id,
    applicants[2].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'SUBMITTED',
    {
      propertyName: 'Fernandes Boutique Hotel',
      location: 'Fontainhas, Panaji',
      area: '1500 sqm',
      rooms: 15,
    },
    'GOA-RL-2024-0006',
    randomDate(2),
    [{ id: fireDeptId, status: 'PENDING' }],
    'stage_1_fire',
  );

  createLicenseRequest(
    applicants[3].id,
    applicants[3].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'SUBMITTED',
    { businessName: 'Desai Textiles', location: 'Margao', businessType: 'Retail - Clothing' },
    'GOA-TL-2024-0006',
    randomDate(2),
    [{ id: municipalityId, status: 'PENDING' }],
    'stage_1_municipality',
  );

  createLicenseRequest(
    applicants[4].id,
    applicants[4].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'SUBMITTED',
    { propertyName: "D'Souza Eco Resort", location: 'Palolem Beach', area: '4500 sqm', rooms: 40 },
    'GOA-RL-2024-0007',
    randomDate(1),
    [{ id: fireDeptId, status: 'PENDING' }],
    'stage_1_fire',
  );

  // REJECTED (3)
  createLicenseRequest(
    applicants[5].id,
    applicants[5].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'REJECTED',
    {
      projectName: 'Shirodkar Beach Construction',
      location: 'CRZ Zone, Calangute',
      floors: 3,
      builtUpArea: '800 sqm',
    },
    'GOA-BP-2024-0005',
    randomDate(20),
    [
      {
        id: revenueDeptId,
        status: 'REJECTED',
        remarks: 'Property falls under CRZ-I zone. Construction not permitted.',
      },
    ],
    'stage_1_revenue',
  );

  createLicenseRequest(
    applicants[6].id,
    applicants[6].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'REJECTED',
    {
      propertyName: 'Pereira Guest House',
      location: 'Candolim Beach Road',
      area: '800 sqm',
      rooms: 10,
    },
    'GOA-RL-2024-0008',
    randomDate(18),
    [
      {
        id: fireDeptId,
        status: 'REJECTED',
        remarks: 'Fire exit width insufficient. Minimum 1.2m required.',
      },
    ],
    'stage_1_fire',
  );

  createLicenseRequest(
    applicants[7].id,
    applicants[7].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'REJECTED',
    {
      businessName: 'Prabhu Fireworks Shop',
      location: 'Residential Area, Margao',
      businessType: 'Retail - Fireworks',
    },
    'GOA-TL-2024-0007',
    randomDate(15),
    [
      {
        id: municipalityId,
        status: 'REJECTED',
        remarks: 'Location not approved for hazardous materials storage.',
      },
    ],
    'stage_1_municipality',
  );

  // DRAFT (3)
  createLicenseRequest(
    applicants[8].id,
    applicants[8].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'DRAFT',
    { propertyName: 'Naik Heritage Villa', location: 'Siolim', area: '2500 sqm', rooms: 20 },
    'GOA-RL-2024-0009',
    randomDate(1),
    [],
    'stage_1_fire',
  );

  createLicenseRequest(
    applicants[9].id,
    applicants[9].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'DRAFT',
    {
      projectName: 'Rodrigues Shopping Mall',
      location: 'Porvorim',
      floors: 4,
      builtUpArea: '5000 sqm',
    },
    'GOA-BP-2024-0006',
    randomDate(1),
    [],
    'stage_1_revenue',
  );

  createLicenseRequest(
    applicants[10].id,
    applicants[10].name,
    'TRADE_LICENSE',
    tradeLicenseWorkflowId,
    'DRAFT',
    { businessName: 'Phadte Bakery', location: 'Ponda', businessType: 'Food & Beverage - Bakery' },
    'GOA-TL-2024-0008',
    randomDate(0),
    [],
    'stage_1_municipality',
  );

  // PENDING_RESUBMISSION (2)
  createLicenseRequest(
    applicants[11].id,
    applicants[11].name,
    'RESORT_LICENSE',
    resortLicenseWorkflowId,
    'PENDING_RESUBMISSION',
    {
      propertyName: 'Shetgaonkar Riverside Resort',
      location: 'Mandovi River Bank',
      area: '3000 sqm',
      rooms: 25,
    },
    'GOA-RL-2024-0010',
    randomDate(12),
    [
      {
        id: fireDeptId,
        status: 'CHANGES_REQUESTED',
        remarks: 'Please submit updated fire escape plan with proper dimensions marked.',
      },
    ],
    'stage_1_fire',
  );

  createLicenseRequest(
    applicants[0].id,
    applicants[0].name,
    'BUILDING_PERMIT',
    buildingPermitWorkflowId,
    'PENDING_RESUBMISSION',
    { projectName: 'Naik Commercial Plaza', location: 'Vasco', floors: 5, builtUpArea: '2000 sqm' },
    'GOA-BP-2024-0007',
    randomDate(10),
    [
      { id: revenueDeptId, status: 'APPROVED', remarks: 'Land ownership confirmed' },
      {
        id: municipalityId,
        status: 'CHANGES_REQUESTED',
        remarks: 'Building plan needs revision for setback requirements. Please resubmit.',
      },
    ],
    'stage_2_municipality',
  );

  // Insert all license requests
  await knex('license_requests').insert(licenseRequests);

  // Insert all documents
  await knex('documents').insert(documents);

  // Insert all document versions
  await knex('document_versions').insert(documentVersions);

  // Insert all approvals (filter out empty arrays)
  if (approvals.length > 0) {
    await knex('approvals').insert(approvals);
  }

  // Insert all workflow states
  await knex('workflow_states').insert(workflowStates);

  // Insert all audit logs
  await knex('audit_logs').insert(auditLogs);

  // Insert blockchain transactions
  if (blockchainTransactions.length > 0) {
    await knex('blockchain_transactions').insert(blockchainTransactions);
  }

  // ============================================
  // WEBHOOKS (for each department)
  // ============================================
  const webhooks = [
    {
      id: uuidv4(),
      department_id: fireDeptId,
      url: 'https://fire.goa.gov.in/api/webhooks/gel',
      events: JSON.stringify([
        'APPROVAL_REQUIRED',
        'DOCUMENT_UPDATED',
        'REQUEST_APPROVED',
        'REQUEST_REJECTED',
      ]),
      secret_hash: await bcrypt.hash('fire_webhook_secret', 10),
      is_active: true,
    },
    {
      id: uuidv4(),
      department_id: tourismDeptId,
      url: 'https://tourism.goa.gov.in/api/webhooks/gel',
      events: JSON.stringify(['APPROVAL_REQUIRED', 'DOCUMENT_UPDATED', 'REQUEST_APPROVED']),
      secret_hash: await bcrypt.hash('tourism_webhook_secret', 10),
      is_active: true,
    },
    {
      id: uuidv4(),
      department_id: municipalityId,
      url: 'https://ccpanaji.goa.gov.in/api/webhooks/gel',
      events: JSON.stringify([
        'APPROVAL_REQUIRED',
        'DOCUMENT_UPDATED',
        'REQUEST_APPROVED',
        'REQUEST_REJECTED',
        'CHANGES_REQUESTED',
      ]),
      secret_hash: await bcrypt.hash('municipality_webhook_secret', 10),
      is_active: true,
    },
    {
      id: uuidv4(),
      department_id: healthDeptId,
      url: 'https://health.goa.gov.in/api/webhooks/gel',
      events: JSON.stringify(['APPROVAL_REQUIRED', 'REQUEST_APPROVED']),
      secret_hash: await bcrypt.hash('health_webhook_secret', 10),
      is_active: true,
    },
    {
      id: uuidv4(),
      department_id: revenueDeptId,
      url: 'https://revenue.goa.gov.in/api/webhooks/gel',
      events: JSON.stringify(['APPROVAL_REQUIRED', 'DOCUMENT_UPDATED']),
      secret_hash: await bcrypt.hash('revenue_webhook_secret', 10),
      is_active: true,
    },
  ];

  await knex('webhooks').insert(webhooks);

  // Print summary
  console.log('\n========================================');
  console.log('GOA-GEL Demo Data Seeded Successfully!');
  console.log('========================================\n');

  console.log('DEPARTMENTS (7):');
  console.log('  - Directorate of Transport, Goa');
  console.log('  - Directorate of Land Revenue, Goa');
  console.log('  - Goa Police Department');
  console.log('  - Goa Tourism Development Corporation');
  console.log('  - Directorate of Health Services, Goa');
  console.log('  - Goa Fire & Emergency Services');
  console.log('  - Corporation of the City of Panaji');

  console.log('\nUSERS:');
  console.log('  Admin:');
  console.log('    - admin@goa.gov.in / Admin@123');
  console.log('  Department Officers:');
  console.log('    - transport@goa.gov.in / Transport@123');
  console.log('    - revenue@goa.gov.in / Revenue@123');
  console.log('    - police@goa.gov.in / Police@123');
  console.log('    - tourism@goa.gov.in / Tourism@123');
  console.log('    - health@goa.gov.in / Health@123');
  console.log('    - fire@goa.gov.in / Fire@123');
  console.log('    - municipality@goa.gov.in / Municipality@123');
  console.log('  Citizens (all password: Citizen@123):');
  console.log('    - rajesh.naik@example.com');
  console.log('    - priya.kamat@example.com');
  console.log('    - antonio.fernandes@example.com');
  console.log('    - sunita.desai@example.com');

  console.log('\nAPPLICANTS: 12 (realistic Goan names)');

  console.log('\nWORKFLOWS (5):');
  console.log('  - RESORT_LICENSE (4 stages: Fire -> Tourism+Municipality -> Health)');
  console.log('  - TRADE_LICENSE (2 stages: Municipality -> Fire)');
  console.log('  - BUILDING_PERMIT (3 stages: Revenue -> Municipality -> Fire)');
  console.log('  - FIRE_SAFETY_CERT (1 stage: Fire)');
  console.log('  - HEALTH_CERT (1 stage: Health)');

  console.log('\nLICENSE REQUESTS (25):');
  console.log('  - APPROVED: 5');
  console.log('  - IN_REVIEW: 7');
  console.log('  - SUBMITTED: 5');
  console.log('  - REJECTED: 3');
  console.log('  - DRAFT: 3');
  console.log('  - PENDING_RESUBMISSION: 2');

  console.log('\nDOCUMENTS: ' + documents.length + ' (4 per request)');
  console.log('APPROVALS: ' + approvals.length);
  console.log('AUDIT LOGS: ' + auditLogs.length);
  console.log('BLOCKCHAIN TRANSACTIONS: ' + blockchainTransactions.length);
  console.log('WEBHOOKS: ' + webhooks.length);

  console.log('\n========================================\n');
}
