<?php

namespace Database\Seeders;

use Exception;
use File;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ReviewTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->seedOldData();
    }

    /**
     * Seed old postshop data
     */
    public function seedOldData(): void
    {
        $datas = json_decode(File::get('database/data/reviews.json'));

        $table = 'reviews';
        foreach ($datas as $data) {
            try {
                DB::table($table)->insert([
                    'id' => $data->id,
                    'rating' => $data->rating,
                    'title' => $data->title,
                    'content' => $data->content,
                    'product_id' => $data->reviewrateable_id,
                    'user_id' => $data->author_id,
                    'is_visible' => $data->approved,
                    'is_recommended' => $data->is_recommended,
                    'created_at' => $data->created_at,
                    'updated_at' => $data->updated_at,
                ]);
            } catch (Exception $e) {
                info(['reviews error: ' => $e->getMessage()]);
            }
        }

        DB::statement("
            SELECT setval('{$table}_id_seq', (SELECT MAX(id) from {$table}))
        ");
    }
}
