<?php

namespace App\Http\Controllers;

use App\Models\Entry;
use App\Models\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ShortLinkController extends Controller
{

    private const array LETTER_TO_TYPE = [
        't' => 'translations',
        'r' => 'romhacks',
        'h' => 'homebrew',
        'u' => 'utilities',
        'd' => 'documents',
        'l' => 'lua-scripts',
    ];

    public function legacy( int $wpId )
    {
        $log = DB::table('migrations_logs')
            ->where('source_system')
            ->whereIn('source_table', ['wp_posts', 'wp_posts__news'] )
            ->where('source_id', $wpId)
            ->first(['target_table', 'target_id']);

        abort_unless((bool)$log, 404);

        if( $log->target_table == 'entries' ){
            $entry = Entry::findOrFail($log->target_id);
            return redirect()->route('entries.show', ['section' => $entry->type, 'entry' => $entry], 301 );
        } else if( $log->target_table == 'news' ){
            $news = News::findOrFail($log->target_id);
            return redirect()->route('news.show', ['news' => $news], 301);
        }

        abort(404);
    }

    public function redirect( string $letter, int $id )
    {
        if( $letter === 'n' ){
            $news = News::findOrFail($id);
            return redirect()->route('news.show', ['news' => $news], 301 );
        }

        $type = self::LETTER_TO_TYPE[$letter] ?? abort(404);
        $entry = Entry::where('id', $id)->where('type', $type)->firstOrFail();

        return redirect()->route('entries.show', ['section' => $entry->type, 'entry' => $entry], 301 );
    }

}
