<?php

use App\Models\JobSource;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        $canonical = DB::table('job_sources')->where('slug', 'weworkremotely')->first();
        $duplicate = DB::table('job_sources')->where('slug', 'we-work-remotely-rss')->first();

        if ($canonical && $duplicate) {
            DB::table('imported_jobs')
                ->where('job_source_id', $duplicate->id)
                ->update(['job_source_id' => $canonical->id]);

            DB::table('job_sources')->where('id', $duplicate->id)->delete();
        } elseif (! $canonical && $duplicate) {
            DB::table('job_sources')
                ->where('id', $duplicate->id)
                ->update([
                    'slug' => 'weworkremotely',
                    'updated_at' => now(),
                ]);
        }

        DB::table('job_sources')->updateOrInsert(
            ['slug' => 'weworkremotely'],
            [
                'name' => 'We Work Remotely RSS',
                'type' => JobSource::TYPE_RSS,
                'request_method' => 'get',
                'base_url' => 'https://weworkremotely.com/',
                'feed_url' => 'https://weworkremotely.com/remote-jobs.rss',
                'attribution_text' => 'Source: We Work Remotely',
                'is_active' => true,
                'auth_type' => JobSource::AUTH_NONE,
                'request_headers' => json_encode([]),
                'query_parameters' => json_encode([]),
                'sync_frequency' => 'hourly',
                'rate_limit_per_minute' => 20,
                'sync_settings' => json_encode([
                    'item_path' => 'channel.item',
                    'title_path' => 'title',
                    'company_path' => 'company',
                    'source_url_path' => 'link',
                    'apply_url_path' => '',
                    'external_id_path' => 'guid',
                    'posted_at_path' => 'pubDate',
                    'category_path' => 'category',
                    'skills_path' => 'skills',
                    'employment_type_path' => 'type',
                    'location_text_path' => 'region',
                    'description_path' => 'description',
                    'split_company_from_title' => true,
                    'timeout' => 20,
                    'expire_missing' => false,
                ]),
                'last_failure_reason' => null,
                'updated_at' => now(),
                'created_at' => now(),
            ]
        );
    }

    public function down(): void
    {
        //
    }
};
