<?php

namespace App\Imports;

use App\Artist;
use App\Song;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class SongsImport implements ToModel, WithHeadingRow, WithValidation
{
    public function model(array $row)
    {
        $title = trim($row['title'] ?? '');
        $lyrics = $row['lyrics'] ?? '';
        $artistsInput = $row['artists'] ?? '';
        $views = isset($row['views']) ? (int) $row['views'] : 0;

        if (!$title) return null;

        $lyrics = str_replace(" | ", "\n", $lyrics);

        $song = Song::firstOrNew(['title' => $title]);
        $song->lyrics = $lyrics;
        $song->views = $views;
        $song->save();

        if ($artistsInput) {
            $artistNames = array_filter(array_map('trim', preg_split('/[\u0026|,+]/u', $artistsInput)));
            $artistIds = [];
            foreach ($artistNames as $name) {
                $artist = Artist::firstOrCreate(['name' => $name]);
                $artistIds[] = $artist->id;
            }
            $song->artists()->sync($artistIds);
        }

        return $song;
    }

    public function rules(): array
    {
        return [
            'title' => 'required|string|max:500',
            'lyrics' => 'nullable|string',
            'artists' => 'nullable|string',
            'views' => 'nullable|integer|min:0',
        ];
    }
}
