const BaseModel = require('./BaseModel');
const { Model } = require('objection');
const { v4: uuidv4 } = require('uuid');

class Mailbox extends BaseModel {
  static get tableName() {
    return 'mailbox';
  }

  static get idColumn() {
    return 'username';
  }

  static get jsonSchema() {
    return {
      type: 'object',
      required: ['username', 'password', 'name', 'domain', 'local_part'],
      
      properties: {
        id: { type: 'string', format: 'uuid', maxLength: 36, default: uuidv4() },
        username: { type: 'string', minLength: 1, maxLength: 255 },
        password: { type: 'string', minLength: 1, maxLength: 255 },
        name: { type: 'string', maxLength: 255 },
        domain: { type: 'string', minLength: 1, maxLength: 255 },
        maildir: { type: 'string', minLength: 1, maxLength: 255 },
        local_part: { type: 'string', minLength: 1, maxLength: 255 },
        quota: { type: 'integer', default: 0 },
        created: { type: 'string', format: 'date-time' },
        modified: { type: 'string', format: 'date-time' },
        active: { type: 'integer', default: 1 },
        phone: { type: 'string', maxLength: 30 },
        email_other: { type: 'string', maxLength: 255 },
        token: { type: 'string', maxLength: 255 },
        token_validity: { type: 'string', format: 'date-time' },
        password_expiry: { type: 'string', format: 'date-time' },
        expires: { type: 'string', format: 'date-time' },
        ignore: { type: 'integer', default: 0 }
      }
    };
  }

  static get relationMappings() {
    const Domain = require('./Domain');
    const FetchMail = require('./FetchMail');
    
    return {
      domainRelation: {
        relation: Model.BelongsToOneRelation,
        modelClass: Domain,
        join: {
          from: 'mailbox.domain',
          to: 'domain.domain'
        }
      },
      fetchMailRelation: {
        relation: Model.HasManyRelation,
        modelClass: FetchMail,
        join: {
          from: 'mailbox.username',
          to: 'fetchmail.mailbox'
        }
      }
    };
  }
}

module.exports = Mailbox;