import { randomUUID } from 'crypto';
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AttendanceRequestPermissions1781020000000
  implements MigrationInterface
{
  name = 'AttendanceRequestPermissions1781020000000';

  private async insertPermissionIfMissing(
    queryRunner: QueryRunner,
    roleSlug: string,
    permissionKey: string,
    permissionValue: string,
  ) {
    await queryRunner.query(
      `INSERT INTO role_permissions (id, role_id, permission_key, permission_value)
       SELECT ?, ar.id, ?, ?
       FROM access_roles ar
       WHERE ar.slug = ?
         AND NOT EXISTS (
           SELECT 1
           FROM role_permissions rp
           WHERE rp.role_id = ar.id
             AND rp.permission_key = ?
         )`,
      [randomUUID(), permissionKey, permissionValue, roleSlug, permissionKey],
    );
  }

  public async up(queryRunner: QueryRunner): Promise<void> {
    const memberPermissions = [
      ['attendance.request.create', 'own'],
      ['attendance.request.view', 'own'],
      ['attendance.request.approve', 'false'],
    ] as const;

    for (const [key, value] of memberPermissions) {
      await this.insertPermissionIfMissing(
        queryRunner,
        'member',
        key,
        value,
      );
    }

    const adminPermissions = [
      ['attendance.request.create', 'all'],
      ['attendance.request.view', 'all'],
      ['attendance.request.approve', 'true'],
    ] as const;

    for (const [key, value] of adminPermissions) {
      await this.insertPermissionIfMissing(queryRunner, 'admin', key, value);
      await this.insertPermissionIfMissing(queryRunner, 'owner', key, value);
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `DELETE FROM role_permissions
       WHERE permission_key IN (
         'attendance.request.create',
         'attendance.request.view',
         'attendance.request.approve'
       )`,
    );
  }
}
