-- V015__create_local_timezone_views.sql
-- UDT-011: Vistas admin con OccurredAt convertido a hora Argentina.
--
-- Crea:
--   dbo.v_AuditEvent_Local   — AuditEvent con OccurredAtLocal (offset -03:00)
--   dbo.v_SecurityEvent_Local — SecurityEvent con OccurredAtLocal (offset -03:00)
--
-- Conversión: OccurredAt AT TIME ZONE 'UTC' AT TIME ZONE 'Argentina Standard Time'
--   → offset fijo -03:00, sin DST (Argentina dejó el horario de verano en 2009).
--   → Nombre 'Argentina Standard Time' es portable: Windows + SQL Server Linux 2022+ (via ICU).
--
-- Idempotente: re-ejecutable. Guard IF OBJECT_ID IS NULL en cada vista.
-- No altera tablas base — rollback seguro sin pérdida de datos.
-- Reversa: V015_ROLLBACK.sql.
-- Run on: SIGCM2 (dev) y SIGCM2_Test (integration tests).
--
-- Covers: REQ-DB-VIEWS-001, REQ-DB-VIEWS-002, REQ-DB-VIEWS-003, REQ-DB-VIEWS-004

SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
GO

-- ═══════════════════════════════════════════════════════════════════════
-- 1. dbo.v_AuditEvent_Local
-- ═══════════════════════════════════════════════════════════════════════
-- Nota: CREATE VIEW no permite IF...BEGIN...END directo — se usa EXEC('CREATE VIEW ...').

IF OBJECT_ID('dbo.v_AuditEvent_Local', 'V') IS NULL
BEGIN
    EXEC('
        CREATE VIEW dbo.v_AuditEvent_Local AS
        SELECT
            Id,
            OccurredAt,
            OccurredAt AT TIME ZONE ''UTC'' AT TIME ZONE ''Argentina Standard Time'' AS OccurredAtLocal,
            ActorUserId,
            ActorRoleId,
            Action,
            TargetType,
            TargetId,
            CorrelationId,
            IpAddress,
            UserAgent,
            Metadata
        FROM dbo.AuditEvent;
    ');
    PRINT 'View dbo.v_AuditEvent_Local created.';
END
ELSE
    PRINT 'View dbo.v_AuditEvent_Local already exists — skip.';
GO

-- ═══════════════════════════════════════════════════════════════════════
-- 2. dbo.v_SecurityEvent_Local
-- ═══════════════════════════════════════════════════════════════════════

IF OBJECT_ID('dbo.v_SecurityEvent_Local', 'V') IS NULL
BEGIN
    EXEC('
        CREATE VIEW dbo.v_SecurityEvent_Local AS
        SELECT
            Id,
            OccurredAt,
            OccurredAt AT TIME ZONE ''UTC'' AT TIME ZONE ''Argentina Standard Time'' AS OccurredAtLocal,
            ActorUserId,
            AttemptedUsername,
            SessionId,
            Action,
            Result,
            FailureReason,
            IpAddress,
            UserAgent,
            Metadata
        FROM dbo.SecurityEvent;
    ');
    PRINT 'View dbo.v_SecurityEvent_Local created.';
END
ELSE
    PRINT 'View dbo.v_SecurityEvent_Local already exists — skip.';
GO

PRINT '';
PRINT 'V015 applied successfully.';
PRINT '  - dbo.v_AuditEvent_Local (AuditEvent + OccurredAtLocal offset -03:00)';
PRINT '  - dbo.v_SecurityEvent_Local (SecurityEvent + OccurredAtLocal offset -03:00)';
PRINT '  - Argentina Standard Time = UTC-3 (fixed offset, no DST since 2009)';
GO
