// SPDX-FileCopyrightText: 2025 Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache-2.0
import type {
  ComponentDto,
  TenantDto,
  VariableAttributeDto,
  VariableCharacteristicsDto,
  VariableDto,
  VariableMonitoringDto,
} from '@citrineos/base';
import { DEFAULT_TENANT_ID, OCPP2_0_1, OCPP2_Namespace } from '@citrineos/base';
import {
  BeforeCreate,
  BeforeUpdate,
  BelongsTo,
  BelongsToMany,
  Column,
  DataType,
  ForeignKey,
  HasMany,
  HasOne,
  Model,
  Table,
} from 'sequelize-typescript';
import { Tenant } from '../Tenant.js';
import { VariableMonitoring } from '../VariableMonitoring/VariableMonitoring.js';
import { Component } from './Component.js';
import { ComponentVariable } from './ComponentVariable.js';
import { VariableAttribute } from './VariableAttribute.js';
import { VariableCharacteristics } from './VariableCharacteristics.js';

@Table({
  indexes: [
    {
      unique: true,
      name: 'variables_tenantId_name',
      fields: ['tenantId', 'name'],
      where: {
        instance: null,
      },
    },
  ],
})
export class Variable extends Model implements OCPP2_0_1.VariableType, VariableDto {
  static readonly MODEL_NAME: string = OCPP2_Namespace.VariableType;

  /**
   * Fields
   */

  @Column({
    type: DataType.STRING,
    unique: 'tenantId_name_instance',
  })
  declare name: string;

  @Column({
    type: DataType.STRING,
    unique: 'tenantId_name_instance',
  })
  declare instance?: string | null;

  /**
   * Relations
   */

  @BelongsToMany(() => Component, { through: () => ComponentVariable, foreignKey: 'variableId' })
  declare components?: ComponentDto[];

  @HasMany(() => VariableAttribute, 'variableId')
  declare variableAttributes?: VariableAttributeDto[];

  @HasOne(() => VariableCharacteristics, 'variableId')
  declare variableCharacteristics?: VariableCharacteristicsDto;

  @HasMany(() => VariableMonitoring, 'variableId')
  declare variableMonitorings?: VariableMonitoringDto[];

  declare customData?: OCPP2_0_1.CustomDataType | null;

  // Declare the association methods, to be automatically generated by Sequelize at runtime
  public addComponent!: (variable: ComponentDto) => Promise<void>;
  public getComponents!: () => Promise<ComponentDto[]>;

  @ForeignKey(() => Tenant)
  @Column({
    type: DataType.INTEGER,
    allowNull: false,
    unique: 'tenantId_name_instance',
    onUpdate: 'CASCADE',
    onDelete: 'RESTRICT',
  })
  declare tenantId: number;

  @BelongsTo(() => Tenant, 'tenantId')
  declare tenant?: TenantDto;

  @BeforeUpdate
  @BeforeCreate
  static setDefaultTenant(instance: Variable) {
    if (instance.tenantId == null) {
      instance.tenantId = DEFAULT_TENANT_ID;
    }
  }

  constructor(...args: any[]) {
    super(...args);
    if (this.tenantId == null) {
      this.tenantId = DEFAULT_TENANT_ID;
    }
  }
}
