<?php

namespace PortalPeople\NgaugeBackupSql\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;

/**
 * BackupHistory Model
 * 
 * Tracks all backup and restore operations.
 * 
 * @property int $id
 * @property string $table_name
 * @property string $filename
 * @property int $file_size
 * @property string $status
 * @property string|null $error_message
 * @property int $created_at
 * @property int|null $created_by
 * 
 * @property-read string $statusLabel Status label for display
 * @property-read string $fileSizeFormatted Formatted file size
 * @property-read string $createdAtFormatted Formatted creation date
 */
class BackupHistory extends ActiveRecord
{
    const STATUS_SUCCESS = 'success';
    const STATUS_FAILED = 'failed';
    const STATUS_RESTORED = 'restored';
    const STATUS_RESTORE_FAILED = 'restore_failed';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%backup_history}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['table_name', 'filename', 'status', 'created_at'], 'required'],
            [['file_size', 'created_at', 'created_by'], 'integer'],
            [['error_message'], 'string'],
            [['table_name', 'filename'], 'string', 'max' => 255],
            [['status'], 'string', 'max' => 50],
            [['status'], 'in', 'range' => [
                self::STATUS_SUCCESS,
                self::STATUS_FAILED,
                self::STATUS_RESTORED,
                self::STATUS_RESTORE_FAILED,
            ]],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'table_name' => 'Table Name',
            'filename' => 'Filename',
            'file_size' => 'File Size',
            'status' => 'Status',
            'error_message' => 'Error Message',
            'created_at' => 'Created At',
            'created_by' => 'Created By',
        ];
    }

    /**
     * Get status label for display
     * 
     * @return string
     */
    public function getStatusLabel()
    {
        $labels = [
            self::STATUS_SUCCESS => 'Backup Success',
            self::STATUS_FAILED => 'Backup Failed',
            self::STATUS_RESTORED => 'Restored',
            self::STATUS_RESTORE_FAILED => 'Restore Failed',
        ];
        
        return $labels[$this->status] ?? $this->status;
    }

    /**
     * Get formatted file size
     * 
     * @return string
     */
    public function getFileSizeFormatted()
    {
        if ($this->file_size == 0) {
            return 'N/A';
        }
        
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $bytes = max($this->file_size, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        
        return round($bytes, 2) . ' ' . $units[$pow];
    }

    /**
     * Get formatted creation date
     * 
     * @return string
     */
    public function getCreatedAtFormatted()
    {
        return Yii::$app->formatter->asDatetime($this->created_at);
    }

    /**
     * Get recent backup history
     * 
     * @param string|null $tableName Filter by table name
     * @param int $limit Number of records to return
     * @return BackupHistory[]
     */
    public static function getRecent($tableName = null, $limit = 50)
    {
        $query = static::find()
            ->orderBy(['created_at' => SORT_DESC])
            ->limit($limit);
        
        if ($tableName !== null) {
            $query->where(['table_name' => $tableName]);
        }
        
        return $query->all();
    }

    /**
     * Get backup statistics
     * 
     * @return array
     */
    public static function getStatistics()
    {
        return [
            'total_backups' => static::find()->where(['status' => self::STATUS_SUCCESS])->count(),
            'failed_backups' => static::find()->where(['status' => self::STATUS_FAILED])->count(),
            'total_restores' => static::find()->where(['status' => self::STATUS_RESTORED])->count(),
            'failed_restores' => static::find()->where(['status' => self::STATUS_RESTORE_FAILED])->count(),
            'total_size' => static::find()->where(['status' => self::STATUS_SUCCESS])->sum('file_size') ?: 0,
            'latest_backup' => static::find()
                ->where(['status' => self::STATUS_SUCCESS])
                ->orderBy(['created_at' => SORT_DESC])
                ->one(),
        ];
    }
}
