<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use App\Models\Artist;
use Carbon\Carbon;
use App\Jobs\StashAndOptimizeLegacyArtworkJob;

class ImportLegacyUserJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    
    /**
     * Create a new job instance.
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $name = str_replace(' ', '', $this->user->username);
        $email = strtolower(trim($this->user->email));
        $email_verified_at = Carbon::parse($this->user->created_at);
        $this->createUser($name, $email, $email_verified_at);
    }

    private function createUser($name, $email, $email_verified_at)
    {
        $user = User::where('name', $name)->first();
        if (!$user) {
            $user = User::factory()->state([
                'name' => $name,
                'email' => $email,
                'email_verified_at' => $email_verified_at,
                'remember_token' => null,
            ])->create();
        }
        $artist = Artist::where('user_id', $user->id)->first();
        if (!$artist) {
            $artist = Artist::factory()->state([
                'user_id' => $user->id,
                'name' => $this->user->profile->name,
                'avatar' => null,
                'header' => null,
                'location' => $this->user->profile->location ?? 'No Agenda Art Generator',
                'website' => $this->user->profile->website ?? null,
                'bio' => null,
            ])->create();
        }
        foreach ($this->user->artworks as $artwork) {
            StashAndOptimizeLegacyArtworkJob::dispatch($artist, $artwork);
        }
    }
}
