<?php

namespace App\Http\Controllers;

use App\Checklist\CheckPrimaryDomain;
use App\Exceptions\DomainOccupiedException;
use App\Http\Requests\AddDomainRequest;
use App\Http\Requests\DomainRequest;
use App\Http\Resources\SiteDomainListResource;
use App\Master\SiteManager;
use App\Http\Requests\AddSiteUserRequest;
use App\Http\Requests\RemoveSiteUserRequest;
use App\Http\Requests\UpdateSiteUserRequest;
use Illuminate\Http\Response;
use Stancl\Tenancy\Database\Models\Domain;
use Stancl\Tenancy\Exceptions\DomainOccupiedByOtherTenantException;

class SiteDomainController extends Controller
{
    /**
     * Show list of domains assigned to site
     *
     * @param SiteManager $manager
     * @return SiteDomainListResource
     */
    public function index(SiteManager $manager)
    {
        return new SiteDomainListResource($manager->getDomains(tenant()));
    }

    /**
     * Add domain to a site
     *
     * @param AddSiteUserRequest $request
     * @param SiteManager $manager
     * @return SiteDomainListResource
     */
    public function store(AddDomainRequest $request, SiteManager $manager)
    {
        try {
            $manager->addDomain(tenant(), $request->input('domain'));
            return $this->index($manager);
        } catch (DomainOccupiedByOtherTenantException) {
            throw new DomainOccupiedException($request->input('domain'));
        }
    }

    /**
     * Make domain primary
     *
     * @param UpdateSiteUserRequest $request
     * @param SiteManager $manager
     * @return SiteDomainListResource|Response
     */
    public function makePrimary(DomainRequest $request, Domain $domain, SiteManager $manager)
    {
        $manager->makeDomainPrimary(tenant(), $domain);
        return $this->index($manager);
    }

    /**
     * Verify if domain is pointing to system
     *
     * @param DomainRequest $request
     * @param Domain $domain
     * @return SiteDomainListResource
     */
    public function verify(DomainRequest $request, Domain $domain, SiteManager $manager)
    {
        $domain->update([
            'verified' => new CheckPrimaryDomain()->performCheck($domain)
        ]);
        return $this->index($manager);
    }

    public function force(Domain $domain, SiteManager $manager)
    {
        if ($domain->primary) {
            $domain->force = true;
            $domain->save();
        }
        return $this->index($manager);
    }

    /**
     * Remove domain from site
     *
     * @param RemoveSiteUserRequest $request
     * @param SiteManager $manager
     * @return SiteDomainListResource
     */
    public function destroy(DomainRequest $request, Domain $domain, SiteManager $manager)
    {
        if ($domain->primary != true) {
            $manager->removeDomain($domain);
        }
        return $this->index($manager);
    }
}
