<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\Company;
use App\Models\LarkPushed;

class LarkPushCompanyModuleCommand extends Command
{
    protected $signature = 'lark:push-company-module {--limit=10}';
    protected $description = 'Send company records one by one to Lark webhook URL with pause';

    public function handle(): int
    {
        $webhookId = env('LARK_COMPANY_WEBHOOK_ID');
        if (!$webhookId) {
            $this->error('LARK_COMPANY_WEBHOOK_ID is not set');
            return self::FAILURE;
        }

        if (app()->environment() !== 'production') {
            $this->info('Skipping Lark push company module in non-production environment.');
            return self::SUCCESS;
        }

        $this->info('Starting Lark push company module...');
        Log::info('[Company Module]: Lark push started', [
            'limit' => (int) $this->option('limit'),
            'env'   => app()->environment(),
        ]);

        $url   = 'https://hfbbr1an7s0.sg.larksuite.com/base/automation/webhook/event/' . $webhookId;
        $limit = (int) $this->option('limit');

        $companies = Company::query()
            ->whereNotExists(function ($q) {
                $company = new Company;
                $q->selectRaw(1)
                    ->from('lark_pushed')
                    ->whereColumn('lark_pushed.owner_id', 'companies.id')
                    ->where('lark_pushed.owner_type', $company->getMorphClass())
                    ->where('lark_pushed.is_success', 1);
            })
            ->limit($limit)
            ->get();

        if ($companies->isEmpty()) {
            $this->warn('⚠️ Nothing to push (all already marked success or none found).');
            return self::SUCCESS;
        }

        foreach ($companies as $company) {
            $payload = [
                'id'         => (string) $company->id,
                'name'       => (string) $company->name,
                'reference'  => (string) $company->reference,
                'debtor'     => (string) $company->debtor,
                'created_at' => optional($company->created_at)->format('Y-m-d H:i:s'),
            ];

            try {
                $res  = Http::asJson()->post($url, $payload);
                $json = $res->json();
                $ok = $res->successful() && is_array($json) && (int)($json['code'] ?? -1) === 0;

                LarkPushed::create([
                    'owner_id'   => $company->id,
                    'owner_type' => $company->getMorphClass(),
                    'is_success' => $ok ? 1 : 0,
                ]);

                if ($ok) {
                    $this->info('[Company Module]: ✅ Sent: ' . $company->name . ' | ' . $company->reference);
                } else {
                    $this->error('❌ Failed for ' . $company->name . ': ' . $res->status() . ' ' . $res->body());
                    Log::error('Lark push failed', [
                        'company_id' => $company->id,
                        'status'     => $res->status(),
                        'body'       => $res->body(),
                    ]);
                }
            } catch (\Throwable $e) {
                LarkPushed::create([
                    'owner_id'   => $company->id,
                    'owner_type' => $company->getMorphClass(),
                    'is_success' => 0,
                ]);
                $this->error('❌ Exception for ' . $company->name . ': ' . $e->getMessage());
                Log::error('Lark push exception', [
                    'company_id' => $company->id,
                    'exception'  => $e->getMessage(),
                    'trace'      => $e->getTraceAsString(),
                ]);
            }

            sleep(1);
        }

        $this->info('Finished sending ' . $companies->count() . ' records.');
        Log::info('[Company Module]: Lark push finished', ['count' => $companies->count()]);

        return self::SUCCESS;
    }
}
