<?php

namespace FSPoster\App\Pages\ContentIdeas\Services;

use Exception;
use FSPoster\App\Pages\ContentIdeas\Repositories\ContentIdeaRepository;
use FSPoster\App\Providers\Helpers\Date;
use FSPoster\App\Providers\Helpers\Helper;

class ContentIdeaService
{
    private ContentIdeaRepository $repo;

    public function __construct(ContentIdeaRepository $repo)
    {
        $this->repo = $repo;
    }

    public function getAll(array $filters): array
    {
        [$ideas, $total] = $this->repo->getAll($filters);

        return [
            'ideas' => array_map([$this, 'formatIdea'], $ideas),
            'total' => $total,
        ];
    }

    /**
     * @throws Exception
     */
    public function get(int $id): array
    {
        $idea = $this->repo->find($id);

        if (empty($idea)) {
            throw new Exception(fsp__('Content idea not found'));
        }

        return [
            'idea' => $this->formatIdea($idea),
        ];
    }

    public function save(array $data): array
    {
        if (!empty($data['id'])) {
            if (isset($data['is_starred']) && !isset($data['title'])) {
                $this->repo->update($data['id'], [
                    'is_starred' => $data['is_starred'] ? 1 : 0,
                ]);

                return [];
            }

            $updateData = [
                'title'         => $data['title'],
                'content'       => $data['content'],
                'media_ids'     => json_encode($data['media_ids'] ?? []),
                'link'          => $data['link'] ?? null,
                'first_comment' => $data['first_comment'] ?? null,
            ];

            if (isset($data['is_starred'])) {
                $updateData['is_starred'] = $data['is_starred'] ? 1 : 0;
            }

            $this->repo->update($data['id'], $updateData);

            return [];
        }

        $newId = $this->repo->insert([
            'title'         => $data['title'],
            'content'       => $data['content'],
            'media_ids'     => json_encode($data['media_ids'] ?? []),
            'link'          => $data['link'] ?? null,
            'first_comment' => $data['first_comment'] ?? null,
            'is_starred'    => !empty($data['is_starred']) ? 1 : 0,
            'blog_id'       => Helper::getBlogId(),
        ]);

        return ['id' => $newId];
    }

    public function delete(array $data): array
    {
        if (!$data['all'] && empty($data['include'])) {
            return [];
        }

        if (!$data['all']) {
            $this->repo->deleteByIds($data['include']);
        } elseif (!empty($data['exclude'])) {
            $this->repo->deleteExcept($data['exclude']);
        } else {
            $this->repo->deleteAll();
        }

        return [];
    }

    private function formatIdea(object $idea): array
    {
        $user = get_userdata($idea->created_by);

        return [
            'id'            => (int) $idea->id,
            'title'         => $idea->title,
            'content'       => $idea->content,
            'media_ids'     => json_decode($idea->media_ids ?? '[]', true),
            'link'          => $idea->link,
            'first_comment' => $idea->first_comment,
            'is_starred'    => (bool) $idea->is_starred,
            'created_by'    => [
                'id'    => (int) $idea->created_by,
                'login' => $user->user_login ?? '',
            ],
            'created_at'    => Date::epoch($idea->created_at),
        ];
    }
}
