<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Listing;
use App\Repositories\Contracts\ListingRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ListingController extends Controller
{
    public function __construct(
        protected ListingRepositoryInterface $listingRepository
    ) {}

    public function featured(Request $request): JsonResponse
    {
        $limit = $request->input('limit', 12);
        
        $listings = $this->listingRepository->getFeatured($limit);

        return response()->json([
            'success' => true,
            'data' => $listings->map(function ($listing) {
                return $this->formatListing($listing);
            }),
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        $filters = [
            'min_price' => $request->input('min_price'),
            'max_price' => $request->input('max_price'),
            'condition_id' => $request->input('condition_id'),
            'location' => $request->input('location'),
            'search' => $request->input('search'),
            'sort_by' => $request->input('sort_by', 'created_at'),
            'sort_order' => $request->input('sort_order', 'desc'),
        ];

        $perPage = $request->input('per_page', 12);
        $listings = $this->listingRepository->getApprovedPaginated($perPage, ['specification', 'condition', 'owner'], $filters);

        return response()->json([
            'success' => true,
            'data' => $listings->map(function ($listing) {
                return $this->formatListing($listing);
            }),
            'meta' => [
                'current_page' => $listings->currentPage(),
                'last_page' => $listings->lastPage(),
                'per_page' => $listings->perPage(),
                'total' => $listings->total(),
            ],
        ]);
    }

    public function show(string $uuid): JsonResponse
    {
        $listing = $this->listingRepository->findByUuidWith($uuid);

        if (!$listing) {
            return response()->json([
                'success' => false,
                'message' => 'Listing not found.',
                'data' => [],
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $this->formatListing($listing, true),
        ]);
    }

    public function related(string $uuid, Request $request): JsonResponse
    {
        $limit = $request->input('limit', 4);
        
        $listings = $this->listingRepository->getRelated($uuid, $limit);

        return response()->json([
            'success' => true,
            'data' => $listings->map(function ($listing) {
                return $this->formatListing($listing);
            }),
        ]);
    }

    /**
     * Format listing for API response.
     */
    private function formatListing(Listing $listing, bool $detailed = false): array
    {
        $spec = $listing->specification;
        
        $data = [
            'id' => $listing->uuid,
            'title' => $listing->title,
            'description' => $listing->description,
            'price' => (float) $listing->price,
            'location' => $listing->location,
            'year' => $spec?->year,
            'make' => $spec?->make,
            'model' => $spec?->model,
            'mileage' => $spec?->mileage,
            'condition' => $listing->condition?->name,
            'condition_id' => $listing->condition_id,
            'image_url' => $listing->image_url && is_array($listing->image_url) 
                ? (count($listing->image_url) > 0 ? $listing->image_url[0] : null)
                : null,
            'images' => $listing->image_url && is_array($listing->image_url) ? $listing->image_url : [],
            'dealer' => $listing->owner ? [
                'name' => $listing->owner->fullName,
                'id' => $listing->owner->uuid ?? $listing->owner->id,
            ] : null,
        ];

        if ($detailed) {
            $data['specification'] = [
                'make' => $spec?->make,
                'model' => $spec?->model,
                'year' => $spec?->year,
                'trim' => $spec?->trim,
                'vin' => $spec?->vin,
                'mileage' => $spec?->mileage,
                'body_type' => $spec?->body_type,
                'exterior_color' => $spec?->exterior_color,
                'interior_color' => $spec?->interior_color,
                'transmission' => $spec?->transmission,
                'fuel_type' => $spec?->fuel_type,
                'engine' => $spec?->engine,
                'drivetrain' => $spec?->drivetrain,
            ];
            $data['features'] = $listing->features->pluck('name')->toArray();
            $data['financing_options'] = $listing->financing_options ?? [];
            $data['all_images'] = $listing->image_url && is_array($listing->image_url) ? $listing->image_url : [];
        }

        return $data;
    }
}

