<?php

namespace App\Livewire\Admin;

use App\Models\AppVersion;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Livewire\Component;

class Versions extends Component
{
    public string  $version       = '';
    public string  $name          = '';
    public string  $changelog     = '';
    public string  $status        = 'draft';
    public string  $platform      = 'all';
    public bool    $show_popup    = true;
    public ?string $editingId     = null;
    public ?string $deployStatus  = null;
    public string  $deployMessage = '';

    public function getVersionsProperty()
    {
        return AppVersion::latest()->get();
    }

    public function save(): void
    {
        $this->validate([
            'version'  => 'required',
            'name'     => 'required',
            'status'   => 'required|in:draft,beta,live,rollback',
            'platform' => 'required|in:all,web,app',
        ]);

        $data = [
            'version'     => $this->version,
            'name'        => $this->name,
            'changelog'   => $this->changelog,
            'status'      => $this->status,
            'platform'    => $this->platform,
            'show_popup'  => $this->show_popup,
            'released_at' => $this->status === 'live' ? now() : null,
        ];

        if ($this->editingId) {
            AppVersion::find($this->editingId)->update($data);
        } else {
            AppVersion::create($data);
        }

        $this->reset(['version', 'name', 'changelog', 'show_popup', 'editingId']);
        $this->status   = 'draft';
        $this->platform = 'all';
    }

    public function setLive(string $id): void
    {
        AppVersion::find($id)->update([
            'status'      => 'live',
            'released_at' => now(),
        ]);
    }

    public function edit(string $id): void
    {
        $v = AppVersion::find($id);
        $this->editingId  = $id;
        $this->version    = $v->version;
        $this->name       = $v->name;
        $this->changelog  = $v->changelog ?? '';
        $this->status     = $v->status;
        $this->platform   = $v->platform;
        $this->show_popup = $v->show_popup;
    }

    public function delete(string $id): void
    {
        AppVersion::find($id)->delete();
    }

    public function getGitInfoProperty(): array
    {
        $raw = shell_exec('git -C /aziros log -1 --pretty=format:"%h|%s|%ci" 2>/dev/null');
        if (!$raw) return ['hash' => '—', 'message' => '—', 'date' => '—'];
        [$hash, $message, $date] = array_pad(explode('|', trim($raw), 3), 3, '—');
        return ['hash' => $hash, 'message' => $message, 'date' => $date];
    }

    public function triggerDeploy(): void
    {
        $secret = env('DEPLOY_WEBHOOK_SECRET', '');
        $url    = 'http://10.10.90.103:9000/deploy';

        try {
            $response = Http::withHeaders(['X-Webhook-Secret' => $secret])
                ->timeout(10)
                ->post($url);

            if ($response->successful()) {
                $this->deployStatus  = 'success';
                $this->deployMessage = $response->body() ?: 'Deploy gestartet';
                Cache::put('last_deploy_triggered_at', now()->toIso8601String(), 86400);
            } else {
                $this->deployStatus  = 'error';
                $this->deployMessage = 'HTTP ' . $response->status();
            }
        } catch (\Throwable $e) {
            $this->deployStatus  = 'error';
            $this->deployMessage = $e->getMessage();
        }
    }

    public function render()
    {
        return view('livewire.admin.versions')
            ->layout('layouts.app');
    }
}
