<?php

namespace App\Console\Commands;

use App\Models\ClientDomain;
use App\Models\ClientProduct;
use App\Models\InvoiceItem;
use Illuminate\Console\Command;

class SyncInvoiceItemsRelatedServiceId extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:sync-related-service-ids';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync related_service_id for existing invoice items based on domain_name and product_id';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting to sync related fields for invoice items...');

        $updated = 0;
        $skipped = 0;

        // Process invoice items
        InvoiceItem::with('invoice')
            ->chunk(100, function ($items) use (&$updated, &$skipped) {
                foreach ($items as $item) {
                    $relatedServiceId = null;
                    $relatedType = $item->type; // 'domain' or 'product'
                    $relatedId = null;
                    $needsUpdate = false;

                    // Check if it's a domain item
                    if ($item->type === 'domain' && $item->domain_name) {
                        $domain = ClientDomain::where('domain', $item->domain_name)->first();

                        if ($domain) {
                            $relatedServiceId = $domain->id;
                            $relatedId = $domain->tld_id; // TLD ID
                            $needsUpdate = true;
                        }
                    }

                    // Check if it's a product/service item
                    if ($item->type === 'product' && $item->product_id) {
                        $serviceQuery = ClientProduct::where('product_id', $item->product_id);

                        // If domain_name is set, use it as additional filter
                        if ($item->domain_name) {
                            $serviceQuery->where('domain', $item->domain_name);
                        }

                        $service = $serviceQuery->first();

                        if ($service) {
                            $relatedServiceId = $service->id;
                            $relatedId = $service->product_id; // Products table ID
                            $needsUpdate = true;
                        }
                    }

                    if ($needsUpdate) {
                        $item->update([
                            'related_service_id' => $relatedServiceId,
                            'related_type' => $relatedType,
                            'related_id' => $relatedId,
                        ]);
                        $updated++;
                    } else {
                        $skipped++;
                    }
                }
            });

        $this->info('Sync completed!');
        $this->info("Updated: {$updated} invoice items");
        $this->info("Skipped: {$skipped} invoice items (no matching service/domain found)");

        return 0;
    }
}
