<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ScheduledPost;
use Illuminate\Http\Request;

class ScheduledPostController extends Controller
{
    /**
     * Get all scheduled posts for the authenticated brand.
     */
    public function index()
    {
        $scheduledPosts = ScheduledPost::where('brand_id', auth()->user()->brand_id)
            ->with(['socialAccount', 'campaign'])
            ->get();

        return response()->json($scheduledPosts);
    }

    /**
     * Get a specific scheduled post.
     */
    public function show(ScheduledPost $scheduledPost)
    {
        // Ensure the user can only view their own scheduled posts
        if ($scheduledPost->brand_id != auth()->user()->brand_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $scheduledPost->load(['socialAccount', 'campaign', 'attempts']);

        return response()->json($scheduledPost);
    }

    /**
     * Create a new scheduled post.
     */
    public function store(Request $request)
    {
        $request->validate([
            'social_account_id' => 'required|exists:social_accounts,id',
            'caption' => 'nullable|string|max:2200',
            'media_refs' => 'nullable|array',
            'media_refs.*.url' => 'required_with:media_refs|string',
            'media_refs.*.type' => 'required_with:media_refs|string|in:image,video',
            'publish_time' => 'required|date',
            'timezone' => 'required|string',
            'campaign_id' => 'nullable|exists:campaigns,id',
            'post_visibility' => 'required|in:public,draft',
            'recurrence' => 'nullable|array',
            'approval_required' => 'boolean',
        ]);

        $scheduledPost = ScheduledPost::create([
            'brand_id' => auth()->user()->brand_id,
            'social_account_id' => $request->social_account_id,
            'caption' => $request->caption,
            'media_refs' => $request->media_refs,
            'publish_time' => $request->publish_time,
            'timezone' => $request->timezone,
            'status' => $request->approval_required ? 'pending_approval' : 'scheduled',
            'retry_policy' => [
                'max_attempts' => 3,
                'backoff' => 'exponential',
                'base_delay' => 60,
                'max_delay' => 86400,
                'multiplier' => 2
            ],
            'idempotency_key' => \Illuminate\Support\Str::uuid(),
            'campaign_id' => $request->campaign_id,
            'post_visibility' => $request->post_visibility,
            'recurrence' => $request->recurrence,
            'approval_required' => $request->approval_required,
        ]);

        return response()->json($scheduledPost, 201);
    }

    /**
     * Update a scheduled post.
     */
    public function update(Request $request, ScheduledPost $scheduledPost)
    {
        // Ensure the user can only update their own scheduled posts
        if ($scheduledPost->brand_id != auth()->user()->brand_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $request->validate([
            'social_account_id' => 'sometimes|exists:social_accounts,id',
            'caption' => 'nullable|string|max:2200',
            'media_refs' => 'nullable|array',
            'media_refs.*.url' => 'required_with:media_refs|string',
            'media_refs.*.type' => 'required_with:media_refs|string|in:image,video',
            'publish_time' => 'sometimes|date',
            'timezone' => 'sometimes|string',
            'campaign_id' => 'nullable|exists:campaigns,id',
            'post_visibility' => 'sometimes|in:public,draft',
            'recurrence' => 'nullable|array',
        ]);

        $scheduledPost->update($request->only([
            'social_account_id',
            'caption',
            'media_refs',
            'publish_time',
            'timezone',
            'campaign_id',
            'post_visibility',
            'recurrence',
        ]));

        return response()->json($scheduledPost);
    }

    /**
     * Delete a scheduled post.
     */
    public function destroy(ScheduledPost $scheduledPost)
    {
        // Ensure the user can only delete their own scheduled posts
        if ($scheduledPost->brand_id != auth()->user()->brand_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $scheduledPost->delete();

        return response()->json(['message' => 'Scheduled post deleted successfully']);
    }

    /**
     * Publish a scheduled post immediately.
     */
    public function publishNow(ScheduledPost $scheduledPost)
    {
        // Ensure the user can only publish their own scheduled posts
        if ($scheduledPost->brand_id != auth()->user()->brand_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        // Dispatch job to process the scheduled post immediately
        \App\Jobs\ProcessScheduledPost::dispatch($scheduledPost);

        // Mark as queued
        $scheduledPost->markQueued();

        return response()->json(['message' => 'Post is being published now']);
    }

    /**
     * Reschedule a post.
     */
    public function reschedule(Request $request, ScheduledPost $scheduledPost)
    {
        // Ensure the user can only reschedule their own scheduled posts
        if ($scheduledPost->brand_id != auth()->user()->brand_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $request->validate([
            'publish_time' => 'required|date',
            'timezone' => 'required|string',
        ]);

        $scheduledPost->update([
            'publish_time' => $request->publish_time,
            'timezone' => $request->timezone,
            'status' => 'scheduled',
        ]);

        return response()->json(['message' => 'Post has been rescheduled']);
    }

    /**
     * Cancel a scheduled post.
     */
    public function cancel(ScheduledPost $scheduledPost)
    {
        // Ensure the user can only cancel their own scheduled posts
        if ($scheduledPost->brand_id != auth()->user()->brand_id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $scheduledPost->markCancelled();

        return response()->json(['message' => 'Post has been cancelled']);
    }
}
