// SPDX-FileCopyrightText: 2025 Contributors to the CitrineOS Project
//
// SPDX-License-Identifier: Apache-2.0
import {
  BeforeCreate,
  BeforeUpdate,
  BelongsTo,
  Column,
  DataType,
  ForeignKey,
  Model,
  Table,
} from 'sequelize-typescript';
import {
  DEFAULT_TENANT_ID,
  OCPP2_Namespace,
  type DeleteCertificateStatusEnumType,
  type HashAlgorithmEnumType,
  type TenantDto,
  type ChargingStationDto,
} from '@citrineos/base';
import { ChargingStation } from '../Location/index.js';
import { Tenant } from '../Tenant.js';

@Table
export class DeleteCertificateAttempt extends Model {
  static readonly MODEL_NAME: string = OCPP2_Namespace.DeleteCertificateAttempt;

  @ForeignKey(() => ChargingStation)
  @Column(DataType.INTEGER)
  declare stationId?: number;

  @Column({
    type: DataType.STRING(36),
    allowNull: false,
  })
  declare ocppConnectionName: string;

  @BelongsTo(() => ChargingStation, 'stationId')
  declare station?: ChargingStationDto;

  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  declare hashAlgorithm: HashAlgorithmEnumType;

  @Column(DataType.STRING)
  declare issuerNameHash: string;

  @Column(DataType.STRING)
  declare issuerKeyHash: string;

  @Column(DataType.STRING)
  declare serialNumber: string;

  @Column({
    type: DataType.STRING,
  })
  declare status?: DeleteCertificateStatusEnumType | null;

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

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

  @BeforeCreate
  static async resolveStationId(instance: DeleteCertificateAttempt): Promise<void> {
    if (instance.stationId == null && instance.ocppConnectionName && instance.tenantId != null) {
      const station = await ChargingStation.findOne({
        where: { ocppConnectionName: instance.ocppConnectionName, tenantId: instance.tenantId },
        attributes: ['id'],
      });
      if (station) {
        instance.stationId = station.id;
      }
    }
  }

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

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