import { Model, RelationMappings, RelationMappingsThunk } from 'objection';
import { BaseModel } from './base.model';

export class User extends BaseModel {
  static tableName = 'users';

  id!: string;
  email!: string;
  passwordHash!: string;
  name!: string;
  role!: 'ADMIN' | 'DEPARTMENT' | 'CITIZEN';
  departmentId?: string;
  walletAddress?: string;
  walletEncryptedKey?: string;
  phone?: string;
  isActive!: boolean;
  lastLoginAt?: Date;
  createdAt!: Date;
  updatedAt!: Date;

  // Relations
  department?: Model;

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['email', 'passwordHash', 'name', 'role'],
      properties: {
        id: { type: 'string', format: 'uuid' },
        email: { type: 'string', format: 'email', maxLength: 255 },
        passwordHash: { type: 'string', maxLength: 255 },
        name: { type: 'string', maxLength: 255 },
        role: { type: 'string', enum: ['ADMIN', 'DEPARTMENT', 'CITIZEN'] },
        departmentId: { type: ['string', 'null'], format: 'uuid' },
        walletAddress: { type: ['string', 'null'], maxLength: 42 },
        walletEncryptedKey: { type: ['string', 'null'] },
        phone: { type: ['string', 'null'], maxLength: 20 },
        isActive: { type: 'boolean', default: true },
        lastLoginAt: { type: ['string', 'null'], format: 'date-time' },
        createdAt: { type: 'string', format: 'date-time' },
        updatedAt: { type: 'string', format: 'date-time' },
      },
    };
  }

  static get relationMappings(): RelationMappingsThunk {
    return (): RelationMappings => {
      const { Department } = require('./department.model');
      return {
        department: {
          relation: Model.BelongsToOneRelation,
          modelClass: Department,
          join: {
            from: 'users.department_id',
            to: 'departments.id',
          },
        },
      };
    };
  }
}
