<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Shift\CloseShiftRequest;
use App\Http\Requests\Shift\OpenShiftRequest;
use App\Http\Resources\ShiftResource;
use App\Models\CashDrawerTransaction;
use App\Models\Shift;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class ShiftController extends ApiController
{
    public function open(OpenShiftRequest $request): ShiftResource
    {
        $user = $this->currentUser($request);
        $branchId = $this->currentBranchId($request);

        $existing = Shift::query()
            ->where('branch_id', $branchId)
            ->where('user_id', $user->id)
            ->where('status', 'open')
            ->first();

        if ($existing !== null) {
            throw ValidationException::withMessages([
                'shift' => ['There is already an open shift for this user and branch.'],
            ]);
        }

        $shift = Shift::create([
            'branch_id' => $branchId,
            'user_id' => $user->id,
            'cash_register_id' => $request->integer('cash_register_id') ?: null,
            'opened_at' => now(),
            'opening_float' => $request->input('opening_float', 0),
            'notes' => $request->input('notes'),
            'status' => 'open',
        ]);

        $shift->activities()->create([
            'user_id' => $user->id,
            'activity_type' => 'login',
            'description' => 'Shift opened',
        ]);

        if ((float) $shift->opening_float > 0) {
            CashDrawerTransaction::create([
                'shift_id' => $shift->id,
                'cash_register_id' => $shift->cash_register_id,
                'user_id' => $user->id,
                'type' => 'float_in',
                'amount' => $shift->opening_float,
                'running_balance' => $shift->opening_float,
                'notes' => 'Opening float',
            ]);
        }

        return new ShiftResource($shift);
    }

    public function close(CloseShiftRequest $request, Shift $shift): ShiftResource
    {
        $this->ensureBranchScoped($shift, $this->currentBranchId($request));

        $expectedCash = (float) DB::table('cash_drawer_transactions')
            ->where('shift_id', $shift->id)
            ->sum('amount');

        $closingFloat = (float) $request->input('closing_float');
        $shift->forceFill([
            'closed_at' => now(),
            'closing_float' => $closingFloat,
            'expected_cash' => $expectedCash,
            'cash_variance' => round($closingFloat - $expectedCash, 2),
            'notes' => $request->input('notes', $shift->notes),
            'status' => 'closed',
        ])->save();

        $shift->activities()->create([
            'user_id' => $this->currentUser($request)->id,
            'activity_type' => 'logout',
            'description' => 'Shift closed',
        ]);

        return new ShiftResource($shift);
    }
}
