<?php

namespace App\Models\Environments;

use App\Models\Clients\Client;
use App\Models\Monitoring\Notice;
use App\Models\Monitoring\Report;
use App\Models\Products\LicenseToken;
use App\Models\Support\Support;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Environment extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'environments';

    const ENVIRONMENTS = [
        'local'   => 'Local',
        'develop' => 'Desarrollo',
        'pre'     => 'PreProducción',
        'pro'     => 'Producción',
    ];

    const JIRA_PROJECT_URL = 'https://tresipunt.atlassian.net/browse/';

    protected $fillable = [
        'name',
        'domain',
        'description',
        'version',
        'env',
        'active',
        'client_id',
        'type_id',
        'environment_support_id',
        'has_support',
        'key',
        'lastversion',
        'lastminor',
        'moodletoken',
        'refresh_at',
        'license_token_id',
    ];

    protected $casts = [
        'active'       => 'boolean',
        'has_support'  => 'boolean',
        'refresh_at'   => 'datetime',
    ];

    protected $appends = [
        'supportname',
        'supporttype',
        'supportdays',
        'supporttotal',
        'supportstart',
        'supportend',
        'supportcomment',
        'supportstatus',
    ];

    // -------------------------
    // Relaciones principales
    // -------------------------

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function type()
    {
        return $this->belongsTo(Type::class);
    }

    /**
     * Token de licencia asignado a este entorno
     */
    public function licenseToken()
    {
        return $this->belongsTo(LicenseToken::class);
    }

    public function plugins()
    {
        return $this->hasMany(Plugin::class);
    }

    public function data()
    {
        return $this->hasOne(Data::class);
    }

    public function environmentStats()
    {
        return $this->hasMany(EnvironmentStat::class);
    }

    public function reports()
    {
        return $this->hasMany(Report::class);
    }

    public function updates()
    {
        return $this->hasMany(Update::class);
    }

    public function notices()
    {
        return $this->hasMany(Notice::class);
    }

    public function supports()
    {
        return $this->belongsToMany(Support::class, 'environment_support')
            ->withPivot(['comment', 'start_at', 'end_at'])
            ->withTimestamps();
    }

    // -------------------------
    // Lógica de soporte
    // -------------------------

    protected function get_current_support()
    {
        if (!$this->environment_support_id) {
            return null;
        }

        $enabled = DB::table('environment_support')
            ->where('id', $this->environment_support_id)
            ->first();

        if (!$enabled) {
            return null;
        }

        $sup = Support::find($enabled->support_id);
        if (!$sup) {
            return null;
        }

        $now = now();
        $start = Carbon::createFromFormat('Y-m-d', $enabled->start_at);
        $end   = Carbon::createFromFormat('Y-m-d', $enabled->end_at);

        $days  = $end->diffInDays($now);
        if ($end < $now) {
            $days = -$days;
        }

        return [
            'type'    => $sup->id,
            'name'    => $sup->name,
            'days'    => $days,
            'total'   => $end->diffInDays($start),
            'start'   => $enabled->start_at,
            'end'     => $enabled->end_at,
            'comment' => $enabled->comment,
            'status'  => Support::get_status_support($start, $end),
        ];
    }

    // -------------------------
    // Getters automáticos
    // -------------------------

    public function getSupportnameAttribute()
    {
        return $this->get_current_support()['name'] ?? '';
    }

    public function getSupporttypeAttribute()
    {
        return $this->get_current_support()['type'] ?? '';
    }

    public function getSupportdaysAttribute()
    {
        return $this->get_current_support()['days'] ?? '';
    }

    public function getSupporttotalAttribute()
    {
        return $this->get_current_support()['total'] ?? '';
    }

    public function getSupportstartAttribute()
    {
        return $this->get_current_support()['start'] ?? '';
    }

    public function getSupportendAttribute()
    {
        return $this->get_current_support()['end'] ?? '';
    }

    public function getSupportcommentAttribute()
    {
        return $this->get_current_support()['comment'] ?? '';
    }

    public function getSupportstatusAttribute()
    {
        if (!$this->has_support) {
            return 0;
        }
        return $this->get_current_support()['status'] ?? 0;
    }
}

