/**
 * Seed Test Users Migration
 *
 * Seeds test users for development and testing
 * Password for all users: Password123!
 * Hash generated with Argon2id
 */

import { MigrationInterface, QueryRunner } from 'typeorm';
import { DEFAULT_ORG_ID } from '../seeds/test-organizations.seed';

export class SeedTestUsers1730000000007 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Use fixed organization ID from seed
    const organizationId = DEFAULT_ORG_ID;

    // Pre-hashed password: Password123! (Argon2id)
    // Generated with: argon2.hash('Password123!', { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 4 })
    const passwordHash =
      '$argon2id$v=19$m=65536,t=3,p=4$Uj+yeQiaqgBFqyTJ5FX3Cw$wpRCYORyFwjQFSuO3gpmzh10gx9wjYFOCvVZ8TVaP8Q';

    // Fixed UUIDs for test users (matching existing data in database)
    const users = [
      {
        id: 'c59ae389-da30-4533-be0c-fdfe6ac945de',
        email: 'admin@xpeditis.com',
        passwordHash,
        firstName: 'Admin',
        lastName: 'User',
        role: 'ADMIN',
      },
      {
        id: '496ba881-c055-4b78-b0c0-6c048215253b',
        email: 'manager@xpeditis.com',
        passwordHash,
        firstName: 'Manager',
        lastName: 'User',
        role: 'MANAGER',
      },
      {
        id: '361b409d-a32b-4ff9-a61b-e927450c1daf',
        email: 'user@xpeditis.com',
        passwordHash,
        firstName: 'Regular',
        lastName: 'User',
        role: 'USER',
      },
    ];

    for (const user of users) {
      await queryRunner.query(`
        INSERT INTO "users" (
          "id", "email", "password_hash", "first_name", "last_name", "role",
          "organization_id", "totp_secret", "is_active", "created_at", "updated_at"
        ) VALUES (
          '${user.id}', '${user.email}', '${user.passwordHash}',
          '${user.firstName}', '${user.lastName}', '${user.role}',
          '${organizationId}', NULL, true, NOW(), NOW()
        )
        ON CONFLICT ("email") DO UPDATE SET
          "password_hash" = EXCLUDED."password_hash",
          "organization_id" = EXCLUDED."organization_id",
          "updated_at" = NOW();
      `);
    }

    console.log('✅ Seeded test users successfully');
    console.log('   - admin@xpeditis.com (ADMIN)');
    console.log('   - manager@xpeditis.com (MANAGER)');
    console.log('   - user@xpeditis.com (USER)');
    console.log('   - Password: Password123!');
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Delete test users
    await queryRunner.query(`
      DELETE FROM users WHERE email IN (
        'admin@xpeditis.com',
        'manager@xpeditis.com',
        'user@xpeditis.com'
      );
    `);

    console.log('✅ Removed test users successfully');
  }
}
