<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Settings\CmnBranch;
use App\Models\Services\SchServices;
use App\Models\Employee\SchEmployee;
use App\Models\Website\SiteUrlShortenerMapping;

class PopulateBranchServiceShortenerLinks extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:populate-branch-service-shortener-links';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        CmnBranch::chunk(100, function ($branches) {
            foreach ($branches as $branch) {
                $encodedBranchSlug = rawurlencode($branch->name_slug);

                $services = SchServices::join('sch_employee_services', 'sch_services.id', '=', 'sch_employee_services.sch_service_id')
                            ->whereIn('sch_employee_id', SchEmployee::where('cmn_branch_id', $branch->id)->pluck('id'))
                            ->where('sch_employee_services.status', 1)
                            ->select('sch_services.id', 'sch_services.title_slug')
                            ->distinct()
                            ->get();

                // Insert or update mappings in bulk
                $mappings = $services->map(function ($service) use ($encodedBranchSlug) {
                    $encodedServiceSlug = rawurlencode($service->title_slug);
                    
                    return [
                        'short_code' => $encodedBranchSlug.'_'.$encodedServiceSlug,
                        'url' => route('site.appoinment.mog-booking').'/branch/'.$encodedBranchSlug.'/service'.$encodedBranchSlug,
                        'action_type' => 'slug.branch.service',
                        'encoded_string' => '-',
                        'route' => '/fireworks-appointment-booking/branch/'.$encodedBranchSlug.'/service/'.$encodedServiceSlug,
                        'query_param' => '',
                        'created_at' => now(),
                        'updated_at' => now()
                    ];
                });
                
                SiteUrlShortenerMapping::upsert($mappings->toArray(), ['short_code'], ['action_type', 'url', 'encoded_string', 'route', 'query_param', 'updated_at']);
            }
        });

        $this->info('All branch-service shortener links generated successfully!');
    }
}
